We are given a number N. We need to check if the given number N can be represented as sum of two Great numbers. If yes then print those two great numbers else print no. Great numbers are those which are represented in the form : ((b)*(b+1)*(2*b+1))/6 where b is a natural number. Examples:
Input : N = 35
Output : 5 and 30
Input : 105
Output : 14 and 91
Input : 99
Output : No the given number is not
a sum of two great numbers
As we know ((b)*(b+1)*(2*b+1))/6 where b is a natural number represents the sum of square of first b natural numbers. For example if b = 3 then 1+4+9 = 14. So to check if the input number n can be represented as sum of two great numbers then we will first compute all the great numbers less than n in an array. Then we will use two pointer approach to find the pair than can sum up to the given number n. To compute the array of all the great numbers we will iterate over i=0 to i
#include <iostream> #include <vector> using namespace std;
void countPairs( int arr[], int tar, int size)
{ // Here the array is already sorted
// so we can find the pair in
// O(n) time
int lo = 0, hi = size - 1;
bool check = false ;
while (lo < hi)
{
if (arr[lo] + arr[hi] == tar)
{
check = true ;
// if sum of both pointers is equal to target
cout << arr[lo] << " and " << arr[hi] << endl;
hi--;
}
else if (arr[lo] + arr[hi] < tar)
{
// if sum is less than target then increment
// the lower index to increase the sum
lo++;
}
else
{
// if sum is greater than target then
// decrement the higher index to decrease
// the sum
hi--;
}
}
// if no single pair was found then check
// will be false
if (!check)
cout << "No the given number is not a sum of two great numbers" << endl;
} // Find the two great numbers in O(n) Time and // O(n) auxiliary space void greatNumberComputation( int n)
{ // To precompute all the great numbers
// less than N
vector< int > arr;
// Traverse from 0 to n and add square of
// current i with the sum of previous
// index of array
int temp = 0;
for ( int i = 0; temp < n; i++)
{
temp += i * i;
arr.push_back(temp);
}
int * a = new int [arr.size()];
for ( int i = 0; i < arr.size(); i++)
a[i] = arr[i];
countPairs(a, n, arr.size());
delete [] a;
} // Driver code int main()
{ int n = 105;
greatNumberComputation(n);
return 0;
} // This code is contributed by Utkarsh. |
14 and 91
Time Complexity: O(N)
Auxiliary Space: O(N)
This article is contributed by Sanket Singh 2.