Problem 3:
The prime factors of 13195 are 5,7,13 and 29.
What is the largest prime factor of the number 600851475143.
问题3:
13195的质因数为5,7,13和29。
600851475143最大的质因数是多少?
分析:
600851475143超过了32位int所能表示的范围,这里用double。
思路1:因为分解质因数是唯一的,用该数去依次除以每个整数(直到不能除尽这个整数),然后用商再去试除下个整数,直到商等于某个整数。
思路2:用该数先除以2直到不能除尽,若结果为1,则返回2,若不为1,用商再依次除以大于等于3的奇数(直到除尽该奇数),当商等于某个奇数时,返回该奇数,即为最大
质因数。
思路3:再思路2基础上,可以先将大于等于3的奇数换成事先计算好的质数表,当有限的质数表除尽而依然未找到最大质因数时,按思路2顺序除以大于质数表中最大数的奇数。
思路2程序如下:
解:
#include <stdio.h>
#include <math.h>
#include <limits>
using namespace std;
typedef int INT;
typedef char CHAR;
typedef void VOID;
typedef double DOUBLE;
#define PRINT printf
#define DPRINT printf
DOUBLE MaxPrimeFactor(DOUBLE n)
{
DOUBLE i;
DOUBLE tem;
DOUBLE max;
if(n - 1.99999999999999 < numeric_limits<DOUBLE>::epsilon())
return -1.0;
max = n;
//除尽2
tem = n / 2.0;
while(fabs(tem - (floor(tem))) < numeric_limits<DOUBLE>::epsilon())
{
DPRINT("质因数为:%lf\n", 2.0);
n = tem;
tem = n / 2.0;
}
if(fabs(n-1.0) < numeric_limits<DOUBLE>::epsilon())
return 2.0;
//除尽大于等于3的奇数
for(i=3.0; i<=max; i+=2.0)
{
if(fabs(n-i) < numeric_limits<DOUBLE>::epsilon())
{
DPRINT("质因数为:%lf\n", i);
return i;
}
tem = n / i;
while(fabs(tem - (floor(tem)) < numeric_limits<DOUBLE>::epsilon()))
{
DPRINT("质因数为:%lf\n", i);
n = tem;
tem = n / i;
}
if(fabs(n-1.0) < numeric_limits<DOUBLE>::epsilon())
return i;
}
return -1.0;
}
INT main(INT argc, CHAR *argv[])
{
while(1)
{
PRINT("请输入数字(小于10^16,输入负数退出):\n");
DOUBLE n;
scanf("%lf", &n);
if(n < 0)
break;
DOUBLE res = MaxPrimeFactor(n);
PRINT("最大质因数为:%lf\n", res);
}
return 0;
}