21xrx.com
2024-09-19 09:58:05 Thursday
登录
文章检索 我的文章 写文章
C++代码:判断完全数
2023-07-02 21:59:29 深夜i     --     --
C++ 完全数 判断

完全数是指一个正整数,它的所有因子(包括1但不包括它本身)之和等于它本身。例如,6是完全数,因为6=1+2+3。本文将介绍使用C++语言判断一个数是否为完全数的代码。

代码实现:


#include <iostream>

using namespace std;

int isPerfect(int n) {

  int sum = 0;

  for(int i=1;i<n;i++) {

    if(n%i==0) {

      sum += i;

    }

  }

  if(sum == n)

    return 1;

  

  else

    return 0;

  

}

int main() {

  int n;

  cin >> n;

  if(isPerfect(n))

    cout << n << " is a perfect number." << endl;

  

  else

    cout << n << " is not a perfect number." << endl;

  

  return 0;

}

代码解析:

该程序中定义了一个函数isPerfect,它的参数为一个正整数n,返回值为1或0,表示n是否为完全数。函数中使用for循环遍历1~n-1之间的所有整数,如果是n的因子,则将其累加到sum变量中。最后,判断sum是否等于n,如果相等,则返回1,否则返回0。

在主函数中,读入一个整数n,判断它是否为完全数,如果是,输出“n is a perfect number.”,否则输出“n is not a perfect number.”。程序结束后返回0。

总结:

本文介绍了使用C++语言判断一个数是否为完全数的代码实现。使用该程序可以帮助我们更深入地了解完全数的概念和特性,在编程中更灵活地运用数学知识。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复