我正在尝试构建一个函数以分解数字。在此示例中,我使用数字95和质数列表。结果应为(5,19)。我在做什么错了?
function factorize(number, primes)
global factor = Int64[]
for i in primes
while number % primes[i] == 0
push!(factor, primes[i])
number = number ÷ primes[i]
end
if number ÷ primes[i] != 1
break
end
end
return factor
end
number = 95
primes = (2,3,5,7,11,13,17,19,23, 27, 31)
answer = factorize(number, primes)
println(answer)
答案 0 :(得分:3)
这是一个固定功能:
function factorize(number, primes)
factor = Int64[]
for p in primes
while number % p == 0
push!(factor, p)
number = number ÷ p
end
if number == 1
break
end
end
if number > 1
@warn "factorization failed, not enough primes passed; printing only factors found in primes vector"
end
return factor
end
更改:
global
限定符p in primes
会返回primes
的元素,而不是primes
的索引number == 1
primes
向量不包含所需的所有素数,则进行错误处理请注意,您可以将结果与Primes.jl软件包中的函数factor
进行比较(但我想您希望将此代码作为算法问题)。