翻译成中文,第三题的题目是这样的:
13195的质数因子有5,7,13和29.
600851475143的最大质数因子是多少?
当然这个题目的思路是很简单的
第一:找出他所有的因数,
第二:看他的因数是不是质数;
但是这里要求程序在一分钟内得到结果,
我先来看我最初的设计:
use strict; use warnings; use bignum; my $num; my $i; my $cout=2; while($cout<300425737571) { if(0==600851475143%$cout) { print $cout."\n"; } $cout++; }
C:\WINDOWS\system32\cmd.exe /c perl "F:\perl\c. 71 839 1471 6857 59569 104441 486847 1234169 5753023 10086647 87625999
其实我们在得到71这个因数的同时,我们也得到了另一个因数:8 462 696 833。这里我们可以得出最大的因数是8462696833.所以我们循环的时候把这一点加上。
use strict; use warnings; use bignum; my $num; my $i; my $cout=2; my $another; while($cout<300425737571) { if(0==600851475143%$cout) { $another = 600851475143/$cout; if($another<$cout) { last; } else { print "$cout\n"; print "$another\n"; } } $cout++; }
C:\WINDOWS\system32\cmd.exe /c perl "F:\perl\c.pl" 71 8462696833 839 716151937 1471 408464633 6857 87625999 59569 10086647 104441 5753023 486847 1234169 Hit any key to close this window...然后我们再来筛选质数就可以了。
use strict; use warnings; my @num; my $cout=0; my $num; my $i; @num=qw/71 839 1471 6857 87625999 59569 10086647 104441 5753023 486847 1234169 408464633 716151937 8462696833 /; foreach $num(@num) { for($i=2;$i<$num**0.5;$i++) { if(0==$num%$i) { $cout=1; last; } } print "$num\n" if($cout==0); }
结果如下:
C:\WINDOWS\system32\cmd.exe /c perl "F:\perl\c.pl" 71 839 1471 6857 Hit any key to close this window...所以最后的结果是6875.