Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Pronic numbers in JavaScript
A Pronic number is a number which is the product of two consecutive integers, that is, a number of the form n(n + 1). For example, 6 is a Pronic number because 6 = 2 × 3, and 12 is Pronic because 12 = 3 × 4.
We are required to write a JavaScript function that takes in a number and returns true if it is a Pronic number otherwise returns false.
Understanding Pronic Numbers
The first few Pronic numbers are: 0, 2, 6, 12, 20, 30, 42, 56, 72, 90...
Method 1: Using Square Root Approach
Since a Pronic number is n(n+1), we can find n by taking the square root and checking nearby integers:
const num = 90;
const isPronic = num => {
let nearestSqrt = Math.floor(Math.sqrt(num));
// Check if nearestSqrt * (nearestSqrt + 1) equals num
if (nearestSqrt * (nearestSqrt + 1) === num) {
return true;
}
// Check the previous integer as well
nearestSqrt = nearestSqrt - 1;
if (nearestSqrt * (nearestSqrt + 1) === num) {
return true;
}
return false;
};
console.log(`Is ${num} a Pronic number?`, isPronic(num));
console.log(`Is 12 a Pronic number?`, isPronic(12));
console.log(`Is 15 a Pronic number?`, isPronic(15));
Is 90 a Pronic number? true Is 12 a Pronic number? true Is 15 a Pronic number? false
Method 2: Optimized Single Check
A more efficient approach checks only the floor of the square root:
const isPronicOptimized = (num) => {
let n = Math.floor(Math.sqrt(num));
return n * (n + 1) === num;
};
// Test multiple numbers
const testNumbers = [0, 2, 6, 12, 15, 20, 25, 30, 42];
testNumbers.forEach(num => {
console.log(`${num}: ${isPronicOptimized(num)}`);
});
0: true 2: true 6: true 12: true 15: false 20: true 25: false 30: true 42: true
Method 3: Finding All Pronic Numbers Up to N
Generate all Pronic numbers up to a given limit:
function findPronicNumbers(limit) {
const pronicNumbers = [];
let n = 0;
let pronic = n * (n + 1);
while (pronic
Pronic numbers up to 100:
[0, 2, 6, 12, 20, 30, 42, 56, 72, 90]
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Square Root Approach | O(1) | O(1) | Single number checks |
| Optimized Single Check | O(1) | O(1) | Most efficient for single checks |
| Generate All Up to N | O(?n) | O(?n) | Finding multiple Pronic numbers |
Conclusion
Pronic numbers follow the pattern n(n+1) and can be efficiently identified using the square root method. The optimized single check approach provides O(1) time complexity for determining if a number is Pronic.
