Given an integer N, the task is to check if it is a Centered Square number or not.
Centered Square number Centered Square Number is a centered figurate number that gives the number of dots in a square with a dot in the center and all other dots surrounding the center dot in successive square layers.The first few Centered Square numbers are 1, 5, 13, 25, 41 …
Examples :
Input : N = 5 Output : Yes Explanation : Second Centered Square number is 5. Input : 14 Output : No
Approach :
- The Kth term of the Centered Square number is given as \(K^{th} Term = K^{2} + (K – 1)^{2}\)
- As we have to check that the given number can be expressed as a Centered Square number or not. This can be checked as follows –
\[=> N = K^{2} + (K – 1)^{2} => N = 2*K^{2} – 2*K + 1 => K = \frac{2 + \sqrt{8*N – 4}}{4}\]
- Finally, check the value of computed using this formulae is an integer, which means that N is a Centered Square number.
Implementation :
// C++ implementation to check that
// a number is a Centered Square number or not
#include <bits/stdc++.h>
using namespace std;
// Function to check that the
// number is a Centered Square number
bool isCenteredSquare(int N)
{
float n
= (2 + sqrt(8 * N - 4)) / 4;
// Condition to check if the
// number is a Centered Square number
return (n - (int)n) == 0;
}
// Driver Code
int main()
{
int i = 13;
// Function call
if (isCenteredSquare(i)) {
cout << "Yes";
}
else {
cout << "No";
}
return 0;
}