We all know numbers that are not the square of any number, such as 2, 3, 5, 7, 8, etc. There are N non-square numbers and it is impossible to know every number. So, in this article, we will explain everything about squareless or non-square numbers and ways to find the Nth non-square number in C.
If a number is the square of an integer, the number is called a perfect square. Some examples of perfect square numbers are -
1 is square of 1 4 is square of 2 9 is square of 3 16 is square of 4 25 is square of 5
If a number is not the square of any integer, then the number is called non-square. For example, the first 15 non-square numbers are -
2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19
Here is an example of finding the Nth non-square number -
Input : 2 Output : 3 Explanation : 2nd Non square number is 3 (after 2 which is first non square number) Input : 5 Output : 7 Explanation : 7th Non square number is 7 ( after 2,3,5,6 which are first four non square
After looking at the above example, we can come up with a solution: In order to find the Nth non-square number, we need Start counting from the nth number and check if each integer is a perfect square and don't count
We created a Complete syntax for finding the Nth non-square number in C.
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; // Taking input from the user. int i = 2; // as 0 and 1 are squares of themselves so we start calculating from 2. int cnt = 0; // declaring counter variable; while(cnt != n){// the loop will terminate when out counter will have the same value as n. int a = sqrt(i); if(i != a*a) cnt++; if(cnt != n) i++; } cout << i << "\n"; // printing the nth non square number. }
5
(When we provide 3 as input, we get 5 as output)
Let’s do the above code A brief description.
Step 1 - Get user input and set count to 0.
cin >> n; // Taking input from the user. int i = 2; // as 0 and 1 are squares of themselves so we start calculating from 2. int cnt = 0; // declaring counter variable;
Step 2 - Count non-square numbers and skip square numbers.
while(cnt != n) // the loop will terminate when out counter will have the same value as n.{ int a = sqrt(i); // finding square root using sqrt() function. if(i != a*a) // check whether the number is a perfect square or not. cnt++; // incrementing counter if found non perfect number. if(cnt != n) i++; }
Step 3 - Print the Nth square number.
cout << i << "\n"; // printing the nth non square number.
In this article, we explained non-square numbers and ways to find the Nth non-square number in C. Apart from C, we can also use this program in different programming languages like Java, Python, C or any other language. We hope this article was helpful and informative for you as we have described everything in the simplest way possible.
The above is the detailed content of Use C++ to write code to find the Nth non-square number. For more information, please follow other related articles on the PHP Chinese website!