題目
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
找出一個合數的最大質數因子
13195的質數因子有5,7,13和29.
600851475143的最大質數因子是多少?
解答:這題要注意數據類型的範圍(關於數據類型的範圍在我的博客中有相關文章http://blog.csdn.net/tabyou/article/details/20214819)。總體來講也比較簡單。遍歷所有質數因子並比較得到最大的即可。
Java程序代碼如下。
public class N_3 {
public static void main(String []args)
{
long num = 600851475143L;//long類型最後要加字母L
long i,max = 0;
while(num!=1)
{
i = 2L;
while(num%i!=0)//最終i遍歷的所有質因子
{
i++;
}
if(max<i)
{
max = i;
}
num = num/i;
}
System.out.println(max);
}
}
運行結果:6857