0

Prime numbers

How can I make a program that says if a number is prime or not with al while loop in python?

2nd Mar 2019, 7:00 PM
vicky
8 ответов
+ 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
2nd Mar 2019, 7:43 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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
3rd Mar 2019, 11:36 AM
Denise Roßberg
Denise Roßberg - avatar
+ 2
vicky you have to write a function that returns true or false or whatever you want (but I'm not familiar with python)
2nd Mar 2019, 9:14 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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++
2nd Mar 2019, 9:26 PM
Denise Roßberg
Denise Roßberg - avatar
+ 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.
2nd Mar 2019, 7:14 PM
Tibor Santa
Tibor Santa - avatar
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
2nd Mar 2019, 9:12 PM
vicky
0
Denise Roßberg why do you take the sqrt?
3rd Mar 2019, 10:53 AM
vicky