使用 C++ 查找第 N 个非平方数


我们都知道一些不是任何数字的平方,例如 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 或其他语言)中使用此程序。我们希望您发现本文对您有所帮助和启发,因为我们以尽可能简单的方式描述了所有内容。

更新于: 2021 年 11 月 23 日

185 次浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告

© . All rights reserved.