Given n, find the which is not a perfect square among natural numbers (1, 2, 3, 4, 5, 6, … )


Input : 3
Output : 5
First three non-square numbers are 2, 3
and 5

Input : 5
Output : 7

Input : 16
Output : 20

Looking at the problem statement we can come up to a straight-forward brute-force approach. We can start from n = 1, and start to check if each of them is a perfect square or not. So we can come up to the nth non-square number.

However, the above approach is very slow as it searches for each in every number smaller than the target each time.

We can observe that the series under consideration is 2, 3, 5, 6, 7, 8, , 11, 12, 13, 14, 15, 17, … .
We can come upto the constant time formula for the nth number in this sequence, by inspection.
ans(n) = n + left lfloor frac{1}{2} + sqrt{n}right rfloor .

The correctness of the formula can be proved by the Principle of Mathematical Induction.

The implementation of the above formula is given below.

// CPP program to find n-th non-square number.
#include <bits/stdc++.h>

using namespace std;

// function to find the nth Non-Square Number
int findNthNonSquare(int n)
    // conversion from int to long double is
    // necessary in order to preserve decimal 
    // places after square root.
    long double x = (long double)n;

    // calculating the result
    long double ans = x + floor(0.5 + sqrt(x));

    return (int)ans;

// Driver code
int main()
    // initializing the term number
    int n = 21;

    // Print the result
    cout << "The " << n << "th Non-Square number is ";
    cout << findNthNonSquare(n);

    return 0;
The 21th Non-Square number is 26

Time Complexity mathcal{O}(1) .
Space Complexity mathcal{O}(1)

I am a problem solving enthusiast and I love competitive programming

If you like and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Article Tags :

Please write to us at to report any issue with the above content.

Source link
thanks you RSS link


Please enter your comment!
Please enter your name here