c语言函数判断两个数是不是亲和数
时间: 2023-11-21 21:05:15 浏览: 86
亲和数指两个数,其中一个数所有因子之和等于另一个数,如220的因子和1+2+4+5+10+11+20+22+44+55+110=284,284的因子和1+2+4+71+142=220,因此220与284是一对亲和数。判断两个数是否为亲和数,可以编写以下函数:
```c
int sum_of_factors(int n) {
int i, sum = 0;
for (i = 1; i <= n / 2; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum;
}
int is_amicable(int a, int b) {
if (sum_of_factors(a) == b && sum_of_factors(b) == a) {
return 1;
} else {
return 0;
}
}
```
其中,`sum_of_factors` 函数计算一个数的因子和,`is_amicable` 函数判断两个数是否为亲和数。如果两个数是亲和数,`is_amicable` 函数返回1,否则返回0。
相关问题
C语言编写函数判断一个数是否是素数
以下是两种C语言编写函数判断一个数是否是素数的例子:
1. 不使用函数的代码:
```c
#include <stdio.h>
int main() {
int i = 0;
scanf("%d", &i);
int n = 0;
for (n = 2; n < i; n++) {
if (i % n == 0) {
break;
}
}
if (i == n) {
printf("素数!\n");
} else {
printf("不是素数!\n");
}
return 0;
}
```
2. 使用自定义函数is_prime()的代码:
```c
#include <stdio.h>
int is_prime(int x) {
int n = 0;
for (n = 2; n < x; n++) {
if (x % n == 0) {
break;
}
}
if (x == n) {
return 1;
}
}
int main() {
int i = 0;
scanf("%d", &i);
if (is_prime(i) == 1) {
printf("素数!\n");
} else {
printf("不是素数!\n");
}
return 0;
}
```
用C语言函数输出两个数最大的数
可以使用条件语句来实现,比较两个数的大小,返回最大的数。
以下是一个简单的实现:
```c
#include <stdio.h>
int max(int a, int b) {
if (a > b) {
return a;
} else {
return b;
}
}
int main() {
int x = 10;
int y = 20;
int z = max(x, y);
printf("Max value is %d\n", z);
return 0;
}
```
输出结果为:
```
Max value is 20
```
其中,`max` 函数接受两个整数参数,返回最大的整数。在 `main` 函数中,我们调用 `max` 函数,将结果赋值给变量 `z`,然后使用 `printf` 函数输出最大值。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)