+ 2

How do I write a code to check if a number is prime using if-else statements?

The basics of the code are good to go. I just don't understand how to express that the number has to be divisible by one and itself ONLY.

11th Mar 2022, 3:06 PM
Kamdili Ife Darachukwu
Kamdili Ife Darachukwu - avatar
7 ответов
+ 2
Just use the modulo operator %, and check all the numbers to at least the squar root of the number you want to check. You only have to check the odd numbers > 2. (Two is of course a prime number.) Example: 10: 10 % 2 == 0 -> no prime 11: 11 % 2 != 0; 11 % 3 != 0; 4 no need to check; 5 ** 2 > 11 -> 11 prime! etc.
11th Mar 2022, 3:21 PM
Per Bratthammar
Per Bratthammar - avatar
+ 1
1.Input a number (as integer) 2.Use a for loop (ranging from 2 to the number) and check if the number is divided by them. 3. If it is then print 'not prime' If it's not print 'its prime' [On the third step you can use if/else]
12th Mar 2022, 3:09 AM
JOKER
JOKER - avatar
+ 1
If loops would work, I'd appreciate a solution from that angle too. Thanks.
14th Mar 2022, 9:44 AM
Kamdili Ife Darachukwu
Kamdili Ife Darachukwu - avatar
+ 1
”Check all numbers” implicitly means using a loop, of course. Start coding and try implement what we discussed above: # Check if n is a prime. for i in range(n + 1): <Here comes your code>
14th Mar 2022, 10:57 AM
Per Bratthammar
Per Bratthammar - avatar