质因数分解程序

一、问题描述

质因数分解,给定一个数,求出该数的所有质因数,由大到小输出


二、程序

/*
 * 质因数分解,求一个数的质因数,例如90 = 2*3*3*5 
 */

#include "stdio.h"
#include "stdlib.h"
#include "math.h" 

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;
}


三、运行结果

质因数分解程序_第1张图片

你可能感兴趣的:(算法)