fork download
  1. #include <stdio.h>
  2.  
  3. void factorize(int n, int divisor, int count, int isFirst) {
  4. if (n == 1) {
  5. // 残っている因数があれば出力
  6. if (count > 0) {
  7. if (!isFirst) printf(" × ");
  8. if (count == 1)
  9. printf("%d", divisor);
  10. else
  11. printf("%d^%d", divisor, count);
  12. }
  13. return;
  14. }
  15.  
  16. if (n % divisor == 0) {
  17. // 同じ因数で割れたらカウントだけ増やす
  18. factorize(n / divisor, divisor, count + 1, isFirst);
  19. } else {
  20. // 今までの因数を表示
  21. if (count > 0) {
  22. if (!isFirst) printf(" × ");
  23. if (count == 1)
  24. printf("%d", divisor);
  25. else
  26. printf("%d^%d", divisor, count);
  27. isFirst = 0;
  28. }
  29. // 次の因数で再帰
  30. factorize(n, divisor + 1, 0, isFirst);
  31. }
  32. }
  33.  
  34. int main() {
  35. int n;
  36.  
  37. printf("3以上の整数を入力してください: ");
  38. scanf("%d", &n);
  39.  
  40. printf("%d の素因数分解: ", n);
  41. factorize(n, 2, 0, 1);
  42. printf("\n");
  43.  
  44. return 0;
  45. }
Success #stdin #stdout 0.01s 5280KB
stdin
360
stdout
3以上の整数を入力してください: 360 の素因数分解: 2^3 × 3^2 × 5