Given n, find the nth number which is not a perfect square among natural numbers (1, 2, 3, 4, 5, 6, … )
Examples:
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, 10, 11, 12, 13, 14, 15, 17, … .
We can come upto the constant time formula for the nth number in this sequence, by inspection.
.
The correctness of the formula can be proved by the Principle of Mathematical Induction.
The implementation of the above formula is given below.
C++
#include <bits/stdc++.h>
using namespace std;
int findNthNonSquare( int n)
{
long double x = ( long double )n;
long double ans = x + floor (0.5 + sqrt (x));
return ( int )ans;
}
int main()
{
int n = 16;
cout << "The " << n << "th Non-Square number is " ;
cout << findNthNonSquare(n);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
import java.lang.*;
class GFG
{
static int findNthNonSquare( int n)
{
double x = ( double )n;
double ans = x + Math.floor( 0.5 +
Math.sqrt(x));
return ( int )ans;
}
public static void main(String[] args)
{
int n = 16 ;
System.out.print( "The " + n +
"th Non-Square number is " );
System.out.print(findNthNonSquare(n));
}
}
|
Python3
import math
def findNthNonSquare(n):
x = n;
ans = x + math.floor( 0.5 + math.sqrt(x));
return int (ans);
n = 16 ;
print ( "The" , n, "th Non-Square number is" ,
findNthNonSquare(n));
|
C#
using System;
class GFG
{
static int findNthNonSquare( int n)
{
double x = ( double )n;
double ans = x + Math.Floor(0.5 +
Math.Sqrt(x));
return ( int )ans;
}
public static void Main()
{
int n = 16;
Console.Write( "The " + n +
"th Non-Square " +
"number is " );
Console.Write(findNthNonSquare(n));
}
}
|
PHP
<?php
function findNthNonSquare( $n )
{
$x = $n ;
$ans = $x + floor (0.5 + sqrt( $x ));
return (int) $ans ;
}
$n = 16;
echo "The " . $n .
"th Non-Square number is " ;
echo findNthNonSquare( $n );
?>
|
Javascript
<script>
function findNthNonSquare(n)
{
var x = n;
var ans = x + Math.floor(0.5 + Math.sqrt(x));
return parseInt(ans);
}
var n = 16;
document.write( "The " + n + "th Non-Square number is " );
document.write(findNthNonSquare(n));
</script>
|
Output:
The 16th Non-Square number is 20
Time Complexity O(log(n))
Space Complexity O(1)
Last Updated :
20 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...