Given two integers A and B, the task is to count the number of pronic numbers that are present in the range [A, B].
Examples:
Input: A = 3, B = 20
Output: 3
Explanation: The pronic numbers from the range [3, 20] are 6, 12, 20Input: A = 5000, B = 990000000
Output: 31393
Naive Approach: Follow the given steps to solve the problem:
- Initialize the count of pronic numbers to 0.
- For every number in the range [A, B], check whether it is a pronic integer or not
- If found to be true, increment the count.
- Finally, print the count
Below is the implementation of the above approach:
C++14
// C++ program for // the above approach #include <bits/stdc++.h> using namespace std; // Function to check if x // is a Pronic Number or not bool checkPronic(int x) { for (int i = 0; i <= (int)(sqrt(x)); i++) { // Check for Pronic Number by // multiplying consecutive // numbers if (x == i * (i + 1)) { return true; } } return false; } // Function to count pronic // numbers in the range [A, B] void countPronic(int A, int B) { // Initialise count int count = 0; // Iterate from A to B for (int i = A; i <= B; i++) { // If i is pronic if (checkPronic(i)) { // Increment count count++; } } // Print count cout << count; } // Driver Code int main() { int A = 3, B = 20; // Function call to count pronic // numbers in the range [A, B] countPronic(A, B); return 0; } |
3
Time Complexity: O((B – A) * √(B – A))
Auxiliary Space: O(1)
Efficient Approach: Follow the below steps to solve the problem:
- Define a function pronic(N) to find the count of pronic integers which are ≤ N.
- Calculate the square root of N, say X.
- If product of X and X – 1 is less than or equal to N, return N.
- Otherwise, return N – 1.
- Print pronic(B) – pronic(A – 1) to get the count of pronic integers in the range [A, B]
Below is the implementation of the above approach:
C++14
// C++ program for the above approach #include <bits/stdc++.h> using namespace std; // Function to count pronic // numbers in the range [A, B] int pronic(int num) { // Check upto sqrt N int N = (int)sqrt(num); // If product of consecutive // numbers are less than equal to num if (N * (N + 1) <= num) { return N; } // Return N - 1 return N - 1; } // Function to count pronic // numbers in the range [A, B] int countPronic(int A, int B) { // Subtract the count of pronic numbers // which are <= (A - 1) from the count // f pronic numbers which are <= B return pronic(B) - pronic(A - 1); } // Driver Code int main() { int A = 3; int B = 20; // Function call to count pronic // numbers in the range [A, B] cout << countPronic(A, B); return 0; } |
3
Time Complexity: O(log2(B))
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

