+ 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.
7 Réponses
+ 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.
+ 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]
+ 1
If loops would work, I'd appreciate a solution from that angle too. Thanks.
+ 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>