c语言求10以内平方和的代码
时间: 2024-05-20 08:17:06 浏览: 46
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 1; i <= 10; i++) {
sum += i * i;
}
printf("10以内平方和为:%d", sum);
return 0;
}
相关问题
C语言求1000以内的素数之和
在C语言中,计算1000以内素数之和,可以采用著名的“筛法”算法,即埃拉托斯特尼筛法(Sieve of Eratosthenes)。以下是简单的步骤:
1. 创建一个布尔数组isPrime[1001],初始化所有元素为true,表示从0到1000都是潜在的素数。
2. 遍历从2开始的所有数字(因为0和1不是素数),对于每个素数i:
- 如果isPrime[i]为true,说明i是素数,将它的倍数设置为false,因为它们不可能是素数。
- 遍历i的平方到1000,步长为i,更新相应的isPrime值。
3. 最后遍历整个isPrime数组,把索引为素数的元素位置上的数字加起来,得到的结果就是1000以内的素数之和。
下面是一个简化的C语言代码示例:
```c
#include <stdio.h>
#define LIMIT 1000
int isPrime[LIMIT+1];
int sumOfPrimes = 0;
void sieveOfEratosthenes() {
for (int i = 2; i * i <= LIMIT; i++) {
if (isPrime[i]) {
for (int j = i * i; j <= LIMIT; j += i) {
isPrime[j] = 0;
}
}
}
}
int main() {
// 初始化所有数为素数
for (int i = 2; i <= LIMIT; i++)
isPrime[i] = 1;
sieveOfEratosthenes();
// 计算并打印素数之和
for (int i = 2; i <= LIMIT; i++) {
if (isPrime[i])
sumOfPrimes += i;
}
printf("The sum of prime numbers less than or equal to 1000 is: %d\n", sumOfPrimes);
return 0;
}
```
运行此程序,它会输出1000以内素数之和。
求3000以内亲密数的c语言代码
在C语言中,亲密数是指两个正整数,它们的和等于这两个数的最大公约数的平方。下面是一个简单的C程序,用于找出3000以内的所有亲密数对:
```c
#include <stdio.h>
#include <math.h>
// 定义最大查找范围和计算最大公约数函数
#define MAX_RANGE 3000
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
// 查找并打印亲密数对的函数
void find_closet_numbers() {
for (int i = 1; i <= MAX_RANGE - 1; ++i) {
for (int j = i + 1; j <= MAX_RANGE; ++j) {
// 计算最大公约数和两数之和
int gcd_value = gcd(i, j);
int sum = i + j;
// 如果和是最大公约数的平方,则找到了亲密数对
if (gcd_value * gcd_value == sum) {
printf("%d and %d are a closet number pair\n", i, j);
}
}
}
}
int main() {
find_closet_numbers();
return 0;
}
阅读全文
相关推荐
















