C语言完美数
C语言完美数程序
完美数
在数学中,理想数是等于和的正整数例如,6是一个正整数,可以被1、2和3完全整除。我们知道该数字本身也可以被整除,但是我们将将其添加到除数中。当我们添加这些除数(1 + 2 + 3 = 6)时,它将产生6,它等于我们考虑的数字。因此,我们可以说6是一个完美数字。
找到完美数字有两种方法:
使用循环
在while循环中使用
用于循环
编写一个接受用户输入并检查给定数字是否完美的C程序。
/*C program to check whether the given number is the Perfect number*/
#include<stdio.h>
#include<conio.h>
void main()
{
// declare and initialize the variables
int num, rem, sum = 0, i;
// take an input from the user.
printf("Enter a number\n");
scanf("%d", &num);
// find all divisors and add them
for(i = 1; i < num; i++)
{
rem = num % i;
if (rem == 0)
{
sum = sum + i;
}
}
if (sum == num)
printf(" %d is a Perfect Number");
else
printf("\n %d is not a Perfect Number");
getch();
}
输出
在上面的输出中,循环条件在每次迭代时均得到验证,并且计数器 i 递增1、在循环内,执行各种操作,例如:
步骤1: i = 1,rem = num%i,=> 28%1 =0。这里rem = 0。
步骤2: rem == 0,条件为真。
步骤3: sum = 0 + i,sum = 0 + 1 => 1
//i递增乘1
步骤4: : i = 2,rem = num%i,=> 28%2 =0。这里rem!= 0,条件为true;
总和= 1 + i => 1 +2 = 3
步骤5: i = 3,rem = num%i,=> 28%3 = 1 。这里rem = 0,条件为false;
步骤6: i = 4,rem = num%i,=> 28%4 = 0.这里rem == 0 ,条件为true;
总和= 1 + i => 3 + 4 = 7
同样,检查所有条件;
步骤7: 总和== num,28 == 28,打印消息"输入的数字是一个完美的数字"
在循环中使用
示例2: 创建一个C程序使用while循环查找最合适的数字。
/*Create a C Program to find the perfect number using while loop*/
#include<stdio.h>
#include<conio.h>
void main()
{
int i = 1, num, Sum = 0;
printf(" Enter any number to check Perfect Number \n");
scanf("%d", &num);
while(i < num )
{
if(num % i == 0)
Sum = Sum + i;
i++;
}
if(Sum == num)
printf("\n %d is Perfect Number", num);
else
printf("\n %d is not a Perfect Number", num);
getch();
}
输出
示例3: 通过C程序找到两个数字之间的完美数字。
#include<stdio.h>
#include<conio.h>
void main()
{
int num, Sum = 0, i, Max, Min;
// Take two number from the user: min and max
printf("Enter the minimum and the maximum value\n");
scanf("%d %d", &Min, &Max);
printf("\n Perfect Number between %d and %d are\n ", Min, Max);
for(num = Min; num <= Max; num++)
{
for(i = 1, Sum = 0; i < num; i++)
{
if(num %i == 0)
Sum = Sum + i;
}
if(Sum == num)
printf("%d \t", num);
}
getch();
}
输出