首页 > 后端开发 > C++ > 正文

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

WBOY
发布: 2023-08-30 22:41:19
转载
1149 人浏览过

使用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 或任何其他语言。我们希望本文对您有所帮助且内容丰富,因为我们以尽可能简单的方式描述了所有内容。

以上是使用C++编写代码,找到第N个非平方数的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!