2014-10-04 42 views
-1

所以我有這個程序,需要它寫輸出爲「96是2^5 x 3^1」而不是2x2x2x2x2x3。輸出?素因式分解

int main() { 

     int i, n; 

     // Get the user input. 
     printf("Please enter a number.\n"); 
     scanf("%d", &n); 

     // Print header. 
     printf("The prime factorization of %d is ", n); 

     // Loop through, finding prime factors. 
     int cur_factor = 2; 
     while (cur_factor < n) { 

      // Found a factor. 
      if (n%cur_factor == 0) { 
       printf("%d x ", cur_factor); 
       n = n/cur_factor; 

      } 

      // Going to the next possible factor. 
      else 
       cur_factor++; 
     } 

     // Prints last factor. 
     printf("%d.\n", cur_factor); 

     return 0; 

我需要做什麼? 感謝

+0

嵌套循環看起來像一個很好的起點,其中內循環計算「功率」。 – 2014-10-04 20:59:04

回答

1
while (cur_factor < n) { 

      // Found a factor. 
      while (n%cur_factor == 0) { 

       n = n/cur_factor; 
       count++; 
      } 
      while(count--) 
      printf("%d x ", cur_factor); 
      count=0; 

      // Going to the next possible factor. 
      else 
       cur_factor++; 
     } 
0

使用一個變量power跟蹤的指數,並打印出來。

還使用了while循環由cur_factor直到n不能由該因素分成了不斷分裂n

int cur_factor = 2; 
    int power = 0; 
    while (cur_factor < n) { 

     // Found a factor. 
     while (n % cur_factor == 0) { 
      power++; 
      n = n/cur_factor; 

     } 

     // Going to the next possible factor. 
     if (power > 0) 
      printf("%d^%d x", cur_factor, power); 
     power = 0; 
     cur_factor++; 
     } 
    }