+ 1

How to check if number is prime

.

20th Nov 2018, 5:27 PM
GANGSTER GAMERS
GANGSTER GAMERS - avatar
2 ответов
+ 5
Here's the idea: you probably know that a prime number is a positive integer that has EXACTLY TWO divisors: 1 and itself. So the first few primes are 2, 3, 5, 7, 11, etc. Now say we want to create a function that tests if an integer n is prime. First we check if n is 1 or smaller. Because if it is, then it's automatically not a prime, and we return False. Next, we want to check if it has a divisor bigger than 1 but smaller than itself. To do that, we'll need to iterate over the integers between 2 and n-1. But how to check if n is divisible by an integer? Hint: divisible means zero remainder, so use the % operator. So when n is divisible by one of those numbers, we can immediately conclude that that it is not prime, and we return False. Lastly, if n is not divisible by any of those numbers, it must be a prime, so we return True. Does that make sense? Let me know if something sounds confusing.
20th Nov 2018, 5:44 PM
Kishalaya Saha
Kishalaya Saha - avatar
0
You can go with an i let's say from 2 to sqrt(n) and if you find a divisor you should change the value of a boolean variable to false. You must assume that the number is prime before you even start verifying( the boolean starts with the true value) https://code.sololearn.com/c3jLn2h2GB2k/?ref=app
20th Nov 2018, 7:27 PM
Stefan Secrieru
Stefan Secrieru - avatar