Loading [MathJax]/extensions/tex2jax.js

搜尋此網誌

[C/C++][判斷質數與因數分解]

之前做過判斷質數與質因數分解的程式,那如果不是要列出質因數,而是要列出因數呢?那就更簡單了,把prime()裡的改一改就好了,只要整除就是因數

  1. /*
  2. * File Name: FactorDecomposition.c
  3. * Author: MH
  4. * Since 2011/05/23
  5. * Toolkit: Dev C++
  6. */
  7.  
  8. # include <stdlib.h>
  9. # include <stdio.h>
  10. # include <math.h>
  11.  
  12. int isprime(int);
  13. void factor(int);
  14.  
  15. int main(){
  16.  
  17.     int input;
  18.  
  19.     while(1){
  20.  
  21.         printf("Please input an integer :\n");
  22.         scanf("%d", &input);
  23.  
  24.         if (input <= 1)
  25.             printf("\ninput must larger than 1\n\n");
  26.  
  27.         else if(isprime(input)==0){    // input is not a prime number
  28.             printf("\n%d is not a prime\n\n", input);
  29.             printf("%d's factor are :\n", input);
  30.             prime(input);
  31.             printf("\n\n");
  32.         }
  33.         else    // input is a prime number
  34.             printf("\n%d is a prime number\n\n", input);
  35.  
  36.         system("PAUSE");
  37.         system("CLS");
  38.  
  39.     }
  40.  
  41.     return 0;
  42. }
  43.  
  44. // check if input is a prime number or not
  45. int isprime(int input){
  46.  
  47.     int i, first=1;
  48.  
  49.     for(i=2; i<=sqrt(input); i++){
  50.  
  51.         if(input%i==0){    // not a prime number
  52.             return 0;
  53.         }
  54.  
  55.     }
  56.  
  57.     return 1;
  58. }
  59.  
  60. // find all the factors
  61. void factor(int input){
  62.  
  63.     int i;
  64.  
  65.     for(i=1; i<=input; i++){
  66.  
  67.         if(input%i==0){    // i is a factor of input
  68.             printf("%d  ", i);
  69.         }
  70.  
  71.     }
  72. }

沒有留言:

張貼留言