我们都知道不是任何数字的平方的数字,如 2、3、5、7、8 等。非平方数有 n 个,不可能知道每个数字。因此,在本文中,我们将解释有关无平方数或非平方数的所有内容,以及在 c++ 中查找第 n 个非平方数的方法。
第 n 个非平方数如果一个数是整数的平方,则该数被称为完全平方数。完全平方数的一些例子是 -
1 is square of 14 is square of 29 is square of 316 is square of 425 is square of 5
如果一个数不是任何整数的平方,则该数被称为非平方数。例如,前 15 个非平方数是 -
2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19
如何找到第 n 个非平方数?这里是找到第 n 个非平方数的示例 -
input : 2output : 3explanation : 2nd non square number is 3 (after 2 which is first non square number)input : 5output : 7explanation : 7th non square number is 7 ( after 2,3,5,6 which are first four non square
看了上面的例子,我们可以得出一个解决方案:为了找到第n个非平方数,我们需要从第n个数开始计数,并检查每个整数是否是完全平方数,并且不计数
创建一个 c++ 程序来查找第 n 个非平方数我们创建了一个在 c++ 中查找第 n 个非平方数的完整语法。
示例#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
(当我们提供 3 作为输入时,我们会得到 5 作为输出)
让我们对上述代码进行简要说明。
第 1 步 - 获取用户输入并将计数设置为 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;
第 2 步 - 计算非平方数并跳过平方数。
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++;}
第 3 步 - 打印第 n 个平方数。
cout << i << "\n"; // printing the nth non square number.
结论在本文中,我们解释了非平方数以及在 c++ 中查找第 n 个非平方数的方法。除了 c++ 之外,我们还可以在不同的编程语言中使用该程序,例如 java、python、c 或任何其他语言。我们希望本文对您有所帮助且内容丰富,因为我们以尽可能简单的方式描述了所有内容。
以上就是使用c++编写代码,找到第n个非平方数的详细内容。