fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3.  
  4. // 連結リストのノードを定義する構造体
  5. typedef struct Node {
  6. int data; // 素因数を格納
  7. struct Node* next; // 次のノードへのポインタ
  8. } Node;
  9.  
  10. // 新しいノードを作成する関数
  11. Node* createNode(int value) {
  12. Node* newNode = (Node*)malloc(sizeof(Node));
  13. if (newNode == NULL) {
  14. printf("メモリ確保に失敗しました。\n");
  15. exit(1);
  16. }
  17. newNode->data = value;
  18. newNode->next = NULL;
  19. return newNode;
  20. }
  21.  
  22. int main() {
  23. int n;
  24. Node* head = NULL; // リストの先頭ポインタ
  25. Node* tail = NULL; // リストの末尾ポインタ
  26.  
  27. printf("正の整数を入力してください: ");
  28. if (scanf("%d", &n) != 1 || n <= 0) {
  29. return 1;
  30. }
  31.  
  32. int temp = n;
  33. for (int i = 2; i * i <= temp; i++) {
  34. while (temp % i == 0) {
  35. Node* newNode = createNode(i);
  36. if (head == NULL) {
  37. head = newNode; // 最初の要素なら先頭にする
  38. tail = newNode;
  39. } else {
  40. tail->next = newNode; // 末尾に追加
  41. tail = newNode;
  42. }
  43. temp /= i;
  44. }
  45. }
  46. if (temp > 1) {
  47. Node* newNode = createNode(temp);
  48. if (head == NULL) {
  49. head = newNode;
  50. tail = newNode;
  51. } else {
  52. tail->next = newNode;
  53. tail = newNode;
  54. }
  55. }
  56.  
  57. // リストを表示
  58. printf("%d の素因数分解結果: ", n);
  59. Node* current = head;
  60. while (current != NULL) {
  61. printf("%d", current->data);
  62. if (current->next != NULL) {
  63. printf(" * ");
  64. }
  65. current = current->next;
  66. }
  67. printf("\n");
  68.  
  69. // メモリの解放
  70. current = head;
  71. while (current != NULL) {
  72. Node* nextNode = current->next;
  73. free(current);
  74. current = nextNode;
  75. }
  76.  
  77. return 0;
  78. }
Success #stdin #stdout 0s 5300KB
stdin
24
stdout
正の整数を入力してください: 24 の素因数分解結果: 2 * 2 * 2 * 3