Given n, find the nth number 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, 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.
The 16th Non-Square number is 20
Time Complexity .
- Number of factors of very large number N modulo M where M is any prime number
- Count number of triplets with product equal to given number with duplicates allowed
- Count number of trailing zeros in Binary representation of a number using Bitset
- Find minimum number to be divided to make a number a perfect square
- Find smallest possible Number from a given large Number with same count of digits
- Number of possible permutations when absolute difference between number of elements to the right and left are given
- Number of ways to split a binary number such that every part is divisible by 2
- Total number of possible Binary Search Trees using Catalan Number
- Find the number of positive integers less than or equal to N that have an odd number of digits
- Number of times the largest perfect square number can be subtracted from N
- Minimum divisor of a number to make the number perfect cube
- Maximum number of contiguous array elements with same number of set bits
- Smallest number dividing minimum number of elements in the array | Set 2
- Largest number dividing maximum number of elements in the array
- Smallest number dividing minimum number of elements in the Array
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.