质因数分解程序

时间:2024-11-21 07:28:10
  • /*
  • * 质因数分解,求一个数的质因数,例如90 = 2*3*3*5
  • */
  • #include ""
  • #include ""
  • #include ""
  • bool isPrime(int number)
  • {
  • double dnum = (double)number;
  • int stopNum = sqrt(dnum);
  • for(int i = 2; i <= stopNum; i++)
  • { if(0 == number % i)
  • return false;
  • }
  • return true;
  • }
  • void PrimeFactor(int number)
  • {
  • int factor = 2;
  • if(number == factor && isPrime(factor))
  • {
  • printf("%d\n", factor);
  • return;
  • }
  • while(number != factor)
  • {
  • while(number % factor == 0 && isPrime(factor))
  • {
  • printf("%d ", factor);
  • number /= factor;
  • }
  • factor ++;
  • if(number == factor && isPrime(factor))
  • printf("%d\n", factor);
  • } //while
  • }
  • int main()
  • {
  • printf("input a number:\n");
  • int number;
  • scanf("%d", &number); //例如:90
  • printf("factor(s) of %d is(are) : ", number);
  • PrimeFactor(number); //例如:90 = 2*3*3*5
  • system("pause");
  • return 0;
  • }