Advertisement
Guest User

Untitled

a guest
Dec 19th, 2014
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.85 KB | None | 0 0
  1. #include <stdio.h>
  2. //判斷 x 是否為質數
  3. int isPrime(int x) {
  4. int i;
  5. for (i = 2; i < x; i++) {
  6. //出現 1 及 x 本身以外的因數,所以不是質數
  7. if ( x % i == 0 )
  8. return 0;
  9. }
  10. //全部檢查完沒有 1 及 x 本身以外的因數,是質數
  11. return 1;
  12. }
  13. //計算階乘並印出
  14. void factorial(int n, int *count) {
  15. int i, fac = 1;
  16. //計算 n! = 1 * 2 * 3 * ... * n
  17. for (i = 1; i <= n; i++)
  18. fac *= i;
  19. printf("factorial of %d = %d\n", n, fac);
  20. //計數器 +1
  21. *count += 1;
  22. }
  23. int main() {
  24. int n, count = 0, i, j;
  25. scanf("%d", &n);
  26. //計算 2 到 n 內的質數,若為質數呼叫 factorial 計算階乘
  27. for (i = 2; i <= n; i++) {
  28. if ( isPrime(i) )
  29. factorial(i, &count);
  30. }
  31. printf("factorial called %d times\n", count);
  32. return 0;
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement