Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- //判斷 x 是否為質數
- int isPrime(int x) {
- int i;
- for (i = 2; i < x; i++) {
- //出現 1 及 x 本身以外的因數,所以不是質數
- if ( x % i == 0 )
- return 0;
- }
- //全部檢查完沒有 1 及 x 本身以外的因數,是質數
- return 1;
- }
- //計算階乘並印出
- void factorial(int n, int *count) {
- int i, fac = 1;
- //計算 n! = 1 * 2 * 3 * ... * n
- for (i = 1; i <= n; i++)
- fac *= i;
- printf("factorial of %d = %d\n", n, fac);
- //計數器 +1
- *count += 1;
- }
- int main() {
- int n, count = 0, i, j;
- scanf("%d", &n);
- //計算 2 到 n 內的質數,若為質數呼叫 factorial 計算階乘
- for (i = 2; i <= n; i++) {
- if ( isPrime(i) )
- factorial(i, &count);
- }
- printf("factorial called %d times\n", count);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement