C程序查找给定数字是否为完美数
完美数字是数字;因子之和等于2*数字。
算法
算法在下面解释-
START Step 1: declare int variables and initialized result=0. Step 2: read number at runtime. Step 3: for loop i=1;i<=number;i++ Condition satisfies i. if(number%i==0) ii. result=result+i; Step 4: checking the sum of factors. i. if(result==2*number) ii. print perfect number iii. else print not perfect number STOP
示例
以下是C程序,以查找给定的数字是否为完美数-
#include<stdio.h> int main(){ int number,i,result=0;//声明变量并将结果初始化为0 printf("输入数字:"); scanf("%d",&number); for(i=1;i<=number;i++){ if(number%i==0) result=result+i; } if(result==2*number) //检查因子之和==2*数量 printf("perfect number"); else printf("not perfect number"); }输出结果
输出如下-
输入数字:28 perfect number 输入数字:46 not perfect number