DEV Community

Discussion on: Project Euler #3 - Largest Prime Factor

Collapse
 
jurituuti profile image
JuriTuuti • Edited

Julia

function isprime(n)
a = ceil(Int,sqrt(n))+1
a=iseven(a) ? a+1 : a
for i = a:-2:3
if n % i == 0
return false
end
end
return true
end

function largest_prime(number)
sqrt_of_n = ceil(Int,sqrt(number)) # the answer must be less than square root of n
sqrt_of_n=iseven(sqrt_of_n) ? sqrt_of_n+1 : sqrt_of_n #a prime cannot be even, so only check odd numbers
for i = sqrt_of_n:-2:1

if number % i == 0 #if 600851475143 is divisible by i
if isprime(i) #then check if i is prime
return i
break
end
end
end
end

println(largest_prime(600851475143))

How do I enter formatted code on this site?