fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <math.h>
  4.  
  5. // 構造体定義(課題1と同様)
  6. typedef struct Node {
  7. long long prime;
  8. int exponent;
  9. struct Node* next;
  10. } Node;
  11.  
  12. // リストの情報から約数の個数と総和を求めて表示する関数
  13. void calculateDivisors(Node* head) {
  14. long long totalCount = 1; // 個数の積の初期値
  15. long long totalSum = 1; // 総和の積の初期値
  16. Node* current = head;
  17.  
  18. while (current != NULL) {
  19. // 1. 約数の個数の計算: (各指数の数 + 1) を掛け合わせる
  20. totalCount *= (current->exponent + 1);
  21.  
  22. // 2. 約数の総和の計算: 等比数列の和の公式を掛け合わせる
  23. // 分子: p^(e+1) - 1
  24. long long numerator = (long long)pow(current->prime, current->exponent + 1) - 1;
  25. // 分母: p - 1
  26. long long denominator = current->prime - 1;
  27.  
  28. totalSum *= (numerator / denominator);
  29.  
  30. current = current->next; // 次のノードへ移動
  31. }
  32.  
  33. printf("約数の個数: %lld 個\n", totalCount);
  34. printf("約数の総和: %lld\n", totalSum);
  35. }
  36.  
  37. // ※動作確認用のメイン関数(手動でリストを構築してテスト)
  38. int main() {
  39. // 例として 12 = 2^2 * 3^1 (約数は1,2,3,4,6,12の6個、和は28)
  40. Node* n1 = (Node*)malloc(sizeof(Node));
  41. Node* n2 = (Node*)malloc(sizeof(Node));
  42.  
  43. n1->prime = 2; n1->exponent = 2; n1->next = n2;
  44. n2->prime = 3; n2->exponent = 1; n2->next = NULL;
  45.  
  46. calculateDivisors(n1);
  47.  
  48. free(n1);
  49. free(n2);
  50. return 0;
  51. }
Success #stdin #stdout 0.01s 5288KB
stdin
Standard input is empty
stdout
約数の個数: 6 個
約数の総和: 28