0
Prime numbers
How can I make a program that says if a number is prime or not with al while loop in python?
8 Respuestas
+ 6
between 2 and the root of the given number. It is not necessary to check all numbers.
square root of n = sqrt (n)
edit:
a (more or less) pseudocode:
int n = input number
int i = 2
while (i <= sqrt (n)){
if (n % i == 0){ //if n is divisible by i
return false //not a prime number
i++
}
return true //prime number
+ 3
vicky
you have number n = p * q (p and q are the prime factors)
If you find a p >= sqrt(n) there have to be a smaller divisor ... for example a number is divisble by 4 --> it is divisible by 2
Or lets take 15 --> sqrt(15) = 3
all divisors: 3 & 5
you find the 3 --> 15/3 = 5. Why should you check the 5?
https://stackoverflow.com/questions/5811151/why-do-we-check-up-to-the-square-root-of-a-prime-number-to-determine-if-it-is-pr
+ 2
If you are not familiar with functions you can use a boolean.
boolean isPrime = true
n = input
i = 2
while (i <= sqrt (n)){
if (n % i == 0){
isPrime = false
}
i++
}
if (isPrime == true){
print (is prime){
}else{
print (is not prime)
}
Important: first check n% i then i++
+ 1
Use the modulo (remainder) operator that is %
Check the divisibility of the number by all other numbers between 2 and itself. If you find at least one divisible then it is not a prime.
0
Denise Roßberg import math
n = int(input("number?"))
i = 2
while (i <= sqrt(n)):
i += 1
if n % i == 0:
return False
return True
it gives me an error
0
Denise Roßberg why do you take the sqrt?