首页 > 文章列表 > 使用C++编写代码,找到第N个非平方数

使用C++编写代码,找到第N个非平方数

数字 平方 C编程
277 2023-08-26

我们都知道不是任何数字的平方的数字,如 2、3、5、7、8 等。非平方数有 N 个,不可能知道每个数字。因此,在本文中,我们将解释有关无平方数或非平方数的所有内容,以及在 C++ 中查找第 N 个非平方数的方法。

第 N 个非平方数

如果一个数是整数的平方,则该数被称为完全平方数。完全平方数的一些例子是 -

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

如果一个数不是任何整数的平方,则该数被称为非平方数。例如,前 15 个非平方数是 -

2, 3, 5, 6, 7, 8, 10, 11, 12, 13, 14, 15, 17, 18, 19

如何找到第 N 个非平方数?

这里是找到第 N 个非平方数的示例 -

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

看了上面的例子,我们可以得出一个解决方案:为了找到第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 或任何其他语言。我们希望本文对您有所帮助且内容丰富,因为我们以尽可能简单的方式描述了所有内容。