+ 1

Why does it show all numbers instead of prime numbers

for(int i=0;i<111;i++){ if(i%2!=0||i%3!=0||i%5!=0||i%7!=0){ System.out.println(i); should it not show only prime numbers now instead of all the numbers?

3rd Mar 2017, 4:01 PM
Wildman Fizat
Wildman Fizat - avatar
5 Respuestas
+ 12
Ah... okay then, sorry didn't checked that out. Anyway, use loop up to sqrt(111) xD
3rd Mar 2017, 5:09 PM
WittyBit
WittyBit - avatar
+ 11
you have 'or' expression, so if doesnt divides by 2, for example it will immideatly print it. So use logical 'and'(&&) to do the task. Also it will not print prime numbers because you doesn't check all divisors of given number(i)
3rd Mar 2017, 4:16 PM
WittyBit
WittyBit - avatar
+ 3
@Michael: I agree with the logic of && operator. I disagree, though, with the second part: you only have to check divisibility by primes up to sqrt(111). That gives up to 7.
3rd Mar 2017, 4:53 PM
Álvaro
+ 2
If you want to print the prime numbers up to 111, you only have to check if its divisible by 2, 3, 5, 7. It's not necessary to check divisibility by the next prime, which is 11, because if a number n can be written as n=a*b, with a and b primes, if a and b where both greater than sqrt(n), then a*b would be greater than n. (source: http://stackoverflow.com/questions/5811151/why-do-we-check-up-to-the-square-root-of-a-prime-number-to-determine-if-it-is-pr )
3rd Mar 2017, 8:56 PM
Álvaro
0
i now understand the && and || a little more clearer now. Thank you. I still have a question. How does the square root function make my code more efficient. Could you show me an example?
3rd Mar 2017, 8:10 PM
Wildman Fizat
Wildman Fizat - avatar