常用算法及参考算法
(1)累加
(2)累乘
(3)素数
(4)最大公约数
(5)最值问题
(6)迭代法
1. 累加
#include <stdio.h>int main() {int n, i, sum = 0;printf("Enter a positive integer n: ");scanf("%d", &n);for (i = 1; i <= n; i++) {sum += i;}printf("The sum from 1 to %d is: %d\n", n, sum);return 0;
}
2. 累乘
#include <stdio.h>int main() {int n, i, product = 1;printf("Enter a positive integer n: ");scanf("%d", &n);for (i = 1; i <= n; i++) {product *= i;}printf("The product from 1 to %d is: %d\n", n, product);return 0;
}
3. 素数判断
#include <stdio.h>
#include <stdbool.h>bool isPrime(int num) {if (num <= 1) return false;for (int i = 2; i * i <= num; i++) {if (num % i == 0) {return false;}}return true;
}int main() {int num;printf("Enter a positive integer: ");scanf("%d", &num);if (isPrime(num)) {printf("%d is a prime number.\n", num);} else {printf("%d is not a prime number.\n", num);}return 0;
}
4. 最大公约数(最小公倍数可以通过两数乘积除以最大公约数得到)
#include <stdio.h>int gcd(int a, int b) {if (b == 0) return a;return gcd(b, a % b);
}int main() {int a, b, g;printf("Enter two integers: ");scanf("%d %d", &a, &b);g = gcd(a, b);printf("The GCD of %d and %d is: %d\n", a, b, g);// LCM = (a * b) / GCD(a, b)printf("The LCM of %d and %d is: %d\n", a, b, (a * b) / g);return 0;
}
5. 最值问题(这里以找数组中的最大值为例)
#include <stdio.h>int main() {int arr[] = {5, 2, 9, 1, 5, 6};int size = sizeof(arr) / sizeof(arr[0]);int max = arr[0];for (int i = 1; i < size; i++) {if (arr[i] > max) {max = arr[i];}}printf("The maximum value in the array is: %d\n", max);return 0;
}
6. 迭代法(这里以计算平方根为例,使用牛顿法)
#include <stdio.h>
#include <math.h>double sqrt_iter(double x, double epsilon) {double guess = x / 2.0;while (fabs(guess * guess - x) >= epsilon) {guess = (guess + x / guess) / 2.0;}return guess;
}int main() {double x, epsilon;printf("Enter a number and epsilon: ");scanf("%lf %lf", &x, &epsilon);printf("The square root of %.2lf is approximately %.5lf\n", x, sqrt_iter(x, epsilon));return 0;
}
这些示例代码可能需要根据具体需求进行调整。