Check if given number can be represented as sum of two great numbers
Last Updated :
11 Nov, 2023
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
C++
#include <iostream>
#include <vector>
using namespace std;
void countPairs( int arr[], int tar, int size)
{
int lo = 0, hi = size - 1;
bool check = false ;
while (lo < hi)
{
if (arr[lo] + arr[hi] == tar)
{
check = true ;
cout << arr[lo] << " and " << arr[hi] << endl;
hi--;
}
else if (arr[lo] + arr[hi] < tar)
{
lo++;
}
else
{
hi--;
}
}
if (!check)
cout << "No the given number is not a sum of two great numbers" << endl;
}
void greatNumberComputation( int n)
{
vector< int > arr;
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;
}
int main()
{
int n = 105;
greatNumberComputation(n);
return 0;
}
|
Java
Python3
C#
Javascript
Time Complexity: O(N)
Auxiliary Space: O(N)
This article is contributed by Sanket Singh 2.
Share your thoughts in the comments
Please Login to comment...