How the Prime number code in python works? - python

def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True
def all_primes(num):
primes = []
for n in range(2,num+1):
if is_prime(n) is True:
primes.append(n)
return primes
num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)
How does it happens...
What understand is if I enter 10
It will be 10%2= 5...the remainder is 0 so it skip to the next one 9%2 = True there is remainder.
It moves to the next one 9%3 remainder is 0 so it skips to 8% ...,then 7 .......but what I dont understand is 7 if it's check until 7%7 ==0 then how did it add 7 as Prime number???
I'm so confused.
Thank you for any comment

but what I dont understand is 7 if it's check until 7%7 ==0
The range function from the following line:
for i in range(2, num):
goes from 2 to num - 1.
So, the range() function doesn't include the last (stop) number in the result.

You got it wrong. If you enter 10, it wouln't check 10%2 and then 9%2...
It would check 10%2, then 10%3, then 10%4... i.e. it would check 10%i, for i ranging from 2 to 9. However, note that execution in is_prime stops as soon as the remainder is 0:
for i in range(2,num):
if (num % i) == 0:
return False
So if num is 10, only 10%2 would be checked, and since it's 0, it would immediately return false.
If num is 9, for example, it would check 9%2. Since the remainder is not 0, it would move up to checking 9%3. The remainder is 0 there, so it would return false in that case.
If num was 7, it would check 7%2. The remainder is not 0 so it checks 7%3, which is also different from 0, and so on. The last check performed would be 7%6, because for i in range(2,num) means that it will iterate with i ranging from 2 to num-1. In this case, is_prime(7) would return true because 7%i, with i ranging from 2 to 6 is different than 0.

when is_prime is called for number 7, the loop will run from 2 to 6 only. Hence 7%7 will never be checked , returning True for such case.

A prime number, by definition, is a number that is divisible only by itself and 1.
Therefore, your function is_prime gets the number you want to check if it is prime, and try to find any other number that can divide it inside the interval [2, num), this interval is implemented using the function range(2,num) inside the for loop.
If it finds any case, i.e., if the if (num % i) == 0 is satisfied, we know that there is a number which divides it, therefore, by definition it is not a prime number.
After checking the whole list, if you cannot find a divisor, we can say that the number is prime, i.e., the return True on your function.
Example:
You want to check 9
(1st step) num = 9, i = 2. 9%2 != 0, we continue in the loop with next value of i.
(2nd step) num = 9, i = 3. 9%3 == 0, we return False. As we know, 9 can divide by 3.
Another example:
You want to check 7
num = 7, i = 2 7%2 != 0, so we continue in the loop with the next value of i
num = 7, i = 3 7%3 != 0, so we continue in the loop with the next value of i
num = 7, i = 4 7%4 != 0, so we continue in the loop with the next value of i
num = 7, i = 5 7%5 != 0, so we continue in the loop with the next value of i
num = 7, i = 6 7%6 != 0, so we continue in the loop with the next value of i
The if was never fulfilled, therefore we reach the end of the loop and
call the next command, which is return True.

Let's consider the two function separately:
def is_prime(num):
for i in range(2,num):
if (num % i) == 0:
return False
return True
This works like this:
let's consider a number num
get a variable i to assume the value 2
evaluate the condition num % i == 0
if the condition is met, then exit from the function and return False
otherwise increment i by 1 and repeat the last two steps until i is equal to num - 1
exit the function and return True
So, this never gets to evaluate 7 % 7: when num is 7 the last value of i is 6.
def all_primes(num):
primes = []
for n in range(2,num+1):
if is_prime(n) is True:
primes.append(n)
return primes
This gets a number num which is the upper limit of the numbers to consider, then:
it creates an empty list named primes
it loops n from 2 until num + 1 excluded (or num included)
if the result of is_prime(n) is True, it appends the number to the list.
finally, return the list in primes.
Finally the main body of the script:
num = int(input("Enter upper limit: "))
primes = all_primes(num)
print(primes)
gets you a string from the keyboard, convert it to int and assign to num, then call all_primes(num) and assign its result to primes and print the list to screen.
So, when you input 10 from the keyboard, it will check the values from 2 to 10 for being prime with is_prime(), and not from 10 and reducing them, as you seems to suggest.

Related

Problem with finding 10,001th prime number: 1 off

"""7. By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
What is the 10 001st prime number?"""
countprime=0
n=2
def prime(number):
for factors in range(2, number):
if number%factors==0:
return False
break
return True
while countprime!=10001:
if prime(n)==True:
countprime+=1
n+=1
print(n)
The answer is supposed to be 104743, but for some reason my brute force program gets 104744, 1 more. Does anyone know why it is one off?
while countprime != 10001:
if prime(n)==True:
countprime+=1
n+=1
When you find a prime number, you always move on to the next number. So, after finding the correct answer, you add up 1 and get 104744.
Try to firstly add 1, and then check if it's prime.
Here is an example:
n = 1
while countprime != 10001:
n += 1
if prime(n):
countprime += 1
You need to break your loop immediately when countprime == 10001 to leave your variable n untouched. A possible way:
while True:
countprime += prime(n)
if countprime == 10001:
break
n += 1
After your program finds the 10001th prime, the value of n is increased by 1 therefore your output is 1 more than the expected answer.
If you use print(n-1), your program will behave as expected.
You're increasing n one last time before your loop exits. If you increase n before checking if it's prime then your countPrime counter and the corresponding prime number will stay in sync (but you'll have to start n at 1 instead of 2):
n = 1
while countprime != 10001:
n += 1
if prime(n):
countprime += 1

What does 'n' mean in this program (python)?

In the sample program below, I tried to find the even number with the the number I typed in (2, 1, 4, 0) these 4 numbers. The result is 2, but I don't know what (n) means in this program.
a = int(input())
n = 0
while a != 0:
if a % 2 == 0:
n = n + 1
a = int(input())
print(n)
here n is used to count even numbers.
the loop will keep checking whether given input is 0 or not if it is 0 the loop will exit if not it will check whether it is even or odd, if the number is even it will increase the value of n by 1. If you input 10 even numbers the value of n will be 10 respectively.
n is your counter and probably you forgot to make a break from the loop the loop will be an infinite loop you have to add a condetion so that the loop stops like:
while n != 10 :
Or
add if statement
if n < 10 :
break #to quit the loop

Python while-loop for prime number returning unexpected value

I am trying to find the largest prime number in a list (ascending order). I created a while-loop which checks if a number in the list is prime by dividing it by each number less than itself and 'breaking' the loop when it finds a number that has no factor less than itself (greater than 1). This loop is nested in another while-loop which iterates backward through the list.
When I run the code, it keeps returning the number 8 (which is obviously not prime).
I have tried going through the code step-by-step on paper, inserting the variable values and doing the math. I must be miscalculating something.
factors = [2, 3, 4, 6, 8]
b = 1
y = len(factors) - 1
x = factors[y]
z = x - b
while y >= 0:
while b < x:
if x % z == 0:
break
else:
if b == x-1:
print(f'The number {x} is the largest prime in the list')
break #need to end the outer loop here
else:
b +=1
y -= 1
b = 1
print('There were no prime numbers in the list')
I expect the code to return 'The number 3 is the largest prime in the list'
What it actually returns:
The number 8 is the largest prime factor
The number 8 is the largest prime factor
The number 8 is the largest prime factor
The number 8 is the largest prime factor
The number 8 is the largest prime factor
A few main problems with your code:
You are not updating the values of x (outer loop) and z (inner loop) on each iteration. You will want to add for z:
else:
b += 1
z = x - b
and for x:
y -= 1
x = factors[y]
b = 1
The fact that you are having that many variables for that task makes it hard to read and understand. You could for example get rid of z all together and simply start b from 2 and go up.
Since both loops iterate over a known range (outer on the list, inner until x) it would be better to use for loops instead of while. That will also arrange your variables better. For example:
factors = [2, 3, 4, 6, 8]
for number in factors[::-1]:
for b in range(2, number):
if number % b == 0:
break
elif b == number-1:
print(f'The number {number} is the largest prime in the list')
break # you should put this whole code in a function and return here
print('There were no prime numbers in the list')
Notice that we don't use any other variables except the ones defined by the loops. That makes the code more readable.
The factors[::-1] means we are looping over the list in reverse order.
A nice little python feature is adding an else clause on a loop. This else will be executed only if the loop is exhausted without meeting any break statement. Which is perfect in our case because if the inner loop is exhausted, then the number is a prime for sure. So it can be:
factors = [2, 3, 4, 6, 8]
for number in factors[::-1]:
for b in range(2, number):
if number % b == 0:
break
else:
print(f'The number {number} is the largest prime in the list')
break # This now breaks the outer loop
else:
print('There were no prime numbers in the list')
Note the use of that same technique also in the outer-loop, as if the inner loop exhausted without hitting the break in the else block, it means no prime was found so we want to print the no-found message.
Can you check the below codes please?
def prime_numbers(numbers):
for i in numbers:
for j in range(2, i):
if i % j == 0:
break
else:
yield i
try:
print(f"{max(prime_numbers([2, 3, 5, 6, 8]))} is the largest prime number.")
except ValueError:
print("There are no prime numbers in the list.")

Range function in prime numbers program

this is a program for printing prime numbers from 2 and 11.
for num in range(2,12):
prime = True
for i in range(2,num):
if (num%i==0):
prime = False
if prime:
print num
In the second for-loop during the last iteration the value of the num=11 .. so the range should take num as 10 i.e (n-1) but in this program value 11 is still getting printed .. how is that?
num is indeed 11, and it is num that is being printed:
if prime:
print num
The range(2, num) range goes from 2 through to 10, inclusive, but the for loop over that range uses i as the target, not num:
for i in range(2, num):
# ^ the target of the for loop
So it is the value of i, not num that goes from 2 through to 10, and i is never printed. The value of num is not changed by the inner loop, it remains set to 11 all the way through. So yes, it'd be surprising if 10 was printed instead.
Note that the print num line is only ever executed if prime is still set to True. It would be set to False if num was divisible by any of the i values. For 11, there is no value between 2 and 10 (inclusive) that can divide 11, so prime remains set to True and num is printed.

What is wrong with my primes number program?

def is_divisible(n, primes):
for i in range(1, len(primes)):
if n % primes[i] == 0:
return True
return False
primes = []
def find_primes(N):
for j in range(1, N):
if is_divisible(j, primes) == False:
primes.append(j)
return primes
print(find_primes(200))
It should tell if a number is prime. And just prints 1.
I think your issue is the indentation of the return statement. Here's your code fixed up:
def is_divisible(n, primes):
for i in range(0, len(primes)):
if n % primes[i] == 0:
return True
return False
def find_primes(N):
primes = []
for j in range(2, N):
if is_divisible(j, primes) == False:
primes.append(j)
return primes
Also avoid globals if you don't have to. find_primes doesnt need to access a global primes list it can declare it locally. Also, notice the range in find_primes that starts at 2 since every number is divisible by 1. Also, indendation matters. In both functions you do not iterate over the entire loop before returning the output (in find_primes) or the default (in is_divisible)
All numbers are divisible by 1. When your program checks if 1 is a prime it determines yes it is so it appends it to the array. Then, when it checks if the next number 2 is divisible by any of the existing primes it says yes, it is divisible by 1 therefore it is not a prime etc etc.
The first number you add is 1, every number is divisible by one and therefore is_divisible(x,1)== True and no number other then 1 is appended to the primes list.
In addition to the remark above (your program should start from 2), you do not want to return until you've completed the 'for j in range((2),N): ' loop. That is, you need to dedent the 'return primes' statement.
Your return primes line is inside the for loop, which means that it just check the first number (i.e. 1), and returns the result of that single calculation.
Your program should instead return the primes after looking at all the number, not just at the first one.

Categories

Resources