
我们都知道不是任何数字的平方的数字,如 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 个非平方数的示例 –
立即学习“C++免费学习笔记(深入)”;
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 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个非平方数的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1444130.html
微信扫一扫
支付宝扫一扫