See the Python code for finding prime numbers between given two numbers lower and upper:
lower = 3
upper = 15
print("Prime numbers between", lower, "and", upper, "are:")
for num in range(lower, upper 1):
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?
CodePudding user response:
Here is the code I would use that keeps the same algorithmic logic per your request (I write this code this way as the condition inside the loop is not only efficient but also reads naturally: "either any of the numbers from the range 2:num-1
divides num
or print num
"):
lower = 3
upper = 15
println("Prime numbers between $lower and $upper are:")
for num in lower:upper
any(i -> num % i == 0, 2:num-1) || println(num)
end
Per comments to your question in Julia you do not have else
clause in for
loop.
However using the any
function keeps the same logic as your code as it is a short-circuting function (achieving the same effect as break
in your for loop).
If anything is not clear in my code please let me know.
EDIT:
I will rewrite the code to explain how it works.
First the ||
part. It uses the short-circuting behavior of ||
operator. So on the first level this can be rewritten as:
lower = 3
upper = 15
println("Prime numbers between $lower and $upper are:")
for num in lower:upper
iscomposite = any(i -> num % i == 0, 2:num-1)
if !iscomposite
println(num)
end
end
Now, as commented any
is doing short circuting also so it is equivalent to writing:
lower = 3
upper = 15
println("Prime numbers between $lower and $upper are:")
for num in lower:upper
iscomposite = false
for i in 2:num-1
if num % i == 0
iscomposite = true
break
end
end
if !iscomposite
println(num)
end
end
CodePudding user response:
Your Julia code seems to print inside and break the factor checking loop instead of waiting for all factors to be verified. (I don't know Julia but that seems to be an obvious difference).