for i in range(2, num):
if (num % i) == 0:
break
else:
print(num)
‘’’
Python Output:
Prime numbers between 3 and 15 are:
3
5
7
11
13
Almost similar code in Julia gives incorrect output. See the Julia code below
‘’'lower = 3
upper = 15
println("Prime numbers between ", lower, " and “, upper, " are:”)
for num in lower:upper
for i in 2: num-1
if (num % i) == 0
break
else
println(num)
break
end
end
end
‘’’ Julia Output:
Prime numbers between 3 and 15 are:
3
5
7
9
11
13
15
Clearly, 9 and 15 are not primes. Why does Python code gives correct output and Julia code does not. Any way to fix it using the same algorithmic logic?
Thanks Kristoffer. Appreciate the help but I don’t understand what you mean . Can you explain in slight detail. I don’t understand when you say " You can use a boolean variable to record if the mod check break never ran." And moreover, I am running else clause for the if condition in my loop in Julia and for “for” loop.
Your code needs to check that (num % i) == 0 is not true for all the numbers in the range and only then print. Right now it oeuvre if it is false for only one number in the range. Remove the last break to make it more obvious.
The code given by you on stack overflow is working correctly but my poor brain couldn’t comprehend it’s logic. If possible kindly explain. Appreciate your help though. Thank you.
The Stack Overflow answer by @bkamins is probably quite clear to experienced Julians, but I suspect it’s difficult to understand for beginners due to the mixed usage of loops and vectorized notation, the anonymous function and the short-circuited ||. Since the question was marked as “New to Julia” I think it might be appropriate to highlight how simple Julia code can be.
In this case I think an extra isprime() function improves readability and hides the loop breaking awkwardness, so here’s my suggestion:
function isprime(num)
for j = 2:num-1
if (num % j) == 0
return false
end
end
return true
end
function primesbetween(lower, upper)
println("Prime numbers between $lower and $upper are:")
for n in lower:upper
if isprime(n)
println(n)
end
end
end
julia> primesbetween(3,15)
Prime numbers between 3 and 15 are:
3
5
7
11
13
I also added primesbetween() to emphasize how Julia code should always be wrapped in functions.
I have edited the code on Stack Overflow with an explanation. Maybe here I would just add that in any(i -> num % i == 0, 2:num-1) the i -> num % i == 0 part defines a function that takes a number i and returns true if i divides num.
I just wanted to stop by to throw in my two sense regarding the provided solution. I’ve personally found that “when in doubt, make a new function”. I’m not sure if the real programmers among the user base agree with that or not, but as a novice, changing my mindset to use functions as a go-to solution for my problems helped me make Julia work for me.