这个问题来自欧拉项目Problem 3:
The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
我个人想到的算法如下:
# 数组里的元素相乘
function multi(arr)
mu = 1
for i in arr
mu *= i
end
return mu
end
function primesF(num::Int64)
primes = [2, 3, 5, 7] # 首先生成简单的质数
p_leng = length(primes) # 由质数所构成的数组的长度
units = [1, 3, 5, 7, 9] # 由于大于10时的质数其个位数无外乎这5个数,在此先罗列
# 开始尝试在已有的质数数组里是否有num的分解质数
for i in primes
while num%i == 0 # 判断i是否为num的分解质数
num = Int64(num / i) # 如果是,让num除以i并返回给num,这意味着num会一直减小,直到i不再是num的分解质数
if num == 1 # 如果num = 1,则i即为原来num的最大分解质数
return i
break
end
end
# 由于初始的质数数组只有4个,下面是用来追加更大的质数的,以防质数不够用
if i == primes[p_leng] && num > primes[p_leng]
units .+= 10
for j in units
if multi(j .% primes) != 0
push!(primes, j)
p_leng += 1
end
end
end
end
end
ts = primesF(5143)
println(ts)
问题是: 当我把600851475143
代入ts = primesF()
时,出现了报错,但是如果你用小的整数,比如ts = primesF(13195)
,还能得到正确的结果,请问为什么换成大的整数就不行了?
报错代码如下:
ERROR: LoadError: ArgumentError: `nothing` should not be printed; use `show`, `repr`, or custom output instead.
Stacktrace:
[1] print(::Base.TTY, ::Nothing) at ./show.jl:566
[2] print(::Base.TTY, ::Nothing, ::Char) at ./strings/io.jl:42
[3] println(::Base.TTY, ::Nothing) at ./strings/io.jl:69
[4] println(::Nothing) at ./coreio.jl:4
[5] top-level scope at none:0
[6] include at ./boot.jl:317 [inlined]
[7] include_relative(::Module, ::String) at ./loading.jl:1038
[8] include(::Module, ::String) at ./sysimg.jl:29
[9] exec_options(::Base.JLOptions) at ./client.jl:229
[10] _start() at ./client.jl:421