I want to fine 6th prime number. why execution is stuck after 3? - python-3.x

Q:
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 10001st prime number?
My code is:
def is_prime(num):
if all(num % i != 0 for i in range(2, num)):
return True
else:
return False
def find_nth_prime(nth):
lst_prime = []
num = 2
while len(lst_prime) < nth:
if is_prime(num):
lst_prime.append(num)
print(len(lst_prime), ":", lst_prime[-1])
num += 1
When I try to run find_nth_prime(6) it get stuck after finding "3" as prime. What am I missing here?

In your if statement inside while loop it keeps repeating at n=4 since n +=1 never happens as 4 is not a prime. Therefore take it out of the if statement.
Try using https://pythontutor.com/. It helps you visualize your code
def find_nth_prime(nth):
lst_prime = []
num = 2
while len(lst_prime) < nth:
if is_prime(num):
lst_prime.append(num)
print(len(lst_prime), ":", lst_prime[-1])
num += 1
Also you can do some improvments to your is_prime function. In that you don't have to take the whole range (2, num). It is enough to take the range 2 to square root of num. (2,int(num**0.5)+1) or use sqrt from python's math library

Related

Twin Primes Python Program

I need to write a Python program that determines whether a given integer input is is a twin prime number or not. If the input number is a twin prime, the program must output true. Otherwise, it must output false.
Please may someone guide me with how this program should be written in Python?
This is what I have done so far. I am stuck at the is_twin_prime function part.
def is_prime(x):
for i in range(2, x):
if x % i == 0:
return False
return True
def is_twin_prime(x):
if is_prime(x) = True:
N = int(input())
for i in range(N):
p = int(input())
if is_twin_prime(p):
print("true")
else:
print("false")
Based on the assumption, that you are trying to determine if N & p are twin primes of one another, I found several issues with your code as follows:
the is_twin_prime function has no False return
the is_prime function always starts with 2 and iteratively checks for prime, this is very inefficient.
To provide an answer, I started with the following factoids about twin_primes:
both numbers must be prime
abs(n-p) == 2
n and p must each have a units digit in [0, 2, 3, 5, 7, 8]
To make the function testing for twin primes as efficient as possible, I eliminated any numbers not meeting the last two cases first, and only if necessary did I generate a list of primes. Also, when generating the primes, I only did it once for the largest number since, once I have the list or the largest both numbers must be in the list.
To make searching for primes more efficient I employed itertools, although this could be done with slightly less efficiency without it's use.
import itertools
def erat2():
D = { }
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = p + q
while x in D or not (x&1):
x += p
D[x] = p
def generatePrimes(given_number):
"""
Returns the prime number <= given_number using
an adaptive sieve of estraothenes approach
"""
return list(itertools.islice(erat2(), given_number))
def is_twinPrime(n, p):
accepted_digits = [0, 2, 3, 5, 7, 8]
if abs(n-p) != 2:
return False
elif n%10 not in accepted_digits and p%10 not in accepted_digits:
return False
else:
primes = generatePrimes(max(n, p))
if n in primes and p in primes:
return True
return False
N = int(input("Enter first number"))
P = int(input(Enter second number"))
print(istwinPrime(N, P)

Printing first combination among various combinations

So I have a question:
Given an even number (greater than 2), return two prime numbers whose sum will be equal to given number. There are several combinations possible. Print only first such pair
This is for additional reference:
*Input: The first line contains T, the number of test cases. The following T lines consist of a number each, for which we'll find two prime numbers.
Note: The number would always be an even number.
Output: For every test case print two prime numbers space separated, such that the smaller number appears first. Answer for each test case must be in a new line.
Constraints: 1 ≤ T ≤ 70
2 < N ≤ 10000
Example:
Input:
5, 74, 1024, 66, 8, 9990
Output: 3 71, 3 1021, 5 61, 3 5, 17 9973
Here is what I tried:
import math
def prime(n):
for i in range(2, int(math.sqrt(n)) + 1):
if n % i == 0:
return False
return True
T = int(input("No of inputs: ")) #T is the no of test cases
input_num = []
for i in range(0,T):
input_num.append(input())
lst2= []
if T in range(1,71):
for i in input_num:
if (i in range(3,1000)) and (i % 2 == 0):
for j in range(0,i):
if prime(j) == True:
lst2.append(j)
for x in lst2:
for y in lst2:
if x + y == j:
print(x,end = ' ')
print(y)
This is only taking inputs but not returning outputs.
Also my code is currently intended for all the combinations but what I want is only the first pair and I am not able to do that
I found a more elegant solution to this problem here. Java, C, C++ etc versions of solution is also present there. I am going to give the python3 solution.
# Python 3 program to find a prime number
# pair whose sum is equal to given number
# Python 3 program to print super primes
# less than or equal to n.
# Generate all prime numbers less than n.
def SieveOfEratosthenes(n, isPrime):
# Initialize all entries of boolean
# array as True. A value in isPrime[i]
# will finally be False if i is Not a
# prime, else True bool isPrime[n+1]
isPrime[0] = isPrime[1] = False
for i in range(2, n+1):
isPrime[i] = True
p = 2
while(p*p <= n):
# If isPrime[p] is not changed,
# then it is a prime
if (isPrime[p] == True):
# Update all multiples of p
i = p*p
while(i <= n):
isPrime[i] = False
i += p
p += 1
# Prints a prime pair with given sum
def findPrimePair(n):
# Generating primes using Sieve
isPrime = [0] * (n+1)
SieveOfEratosthenes(n, isPrime)
# Traversing all numbers to find
# first pair
for i in range(0, n):
if (isPrime[i] and isPrime[n - i]):
print(i,(n - i))
return
# Driven program
n = 74
findPrimePair(n)

How to print prime numbers in the 'list'

I have obtained input from user and put its factors to a new list.How do i check for prime numbers in the list.
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
print(b)
Here you can print the list of factors and then iterate through the list of factors and this program will print out the ones that are prime. Instead of printing it you could also append it to another list by replace the print(n) with something else.
import math
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
print(b)
def is_prime(n): #calling a function
if n == 2:
print(n) #if one of the factors is 2 it prints it because it is a prime number
if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2): #checks for other divisors
if n % divisor == 0:
return False
print(n) #otherwise it prints out the number since it is a prime number
for n in b: #iterates through the list of factors and checks if they are prime
is_prime(n)
If we run this and I input 10 it returns this :
[2, 5]
2
5
EDIT :
When you input a prime number it returns a blank array. So i edited the code to be :
import math
values = []
def is_prime(n): #calling a function
if n == 2:
values.append(n)
#print(n) #if one of the factors is 2 it prints it because it is a prime number
return True
if n % 2 == 0 or n <= 1: # if it is less than one or is a factor of 2 it returns false and does nothing
return False
sqr = int(math.sqrt(n)) + 1
for divisor in range(3, sqr, 2): #checks for other divisors
if n % divisor == 0:
return False
#print(n) #otherwise it prints out the number since it is a prime number
values.append(n)
return True
a=int(input())
b=[]
for x in range(2,a):
if(a%x)==0:
b.append(x)
if is_prime(a)==True: #if the inputted number is prime it automatically appends that number to the list and breaks since prime numbers don't have any other factors
b.append(a)
break;
print(b)
for n in b: #iterates through the list of factors and checks if they are prime
is_prime(n)
def remove_duplicates(values): #here it checks for duplicates
output = []
seen = set()
for value in values:
# If value has not been encountered yet,
# ... add it to both list and set.
if value not in seen:
output.append(value)
seen.add(value)
return output
# Remove duplicates from this list.
values = remove_duplicates(values)
print("Here are the prime factors :")
print(values) #prints out the values
Now if you input a prime number it returns :
[7]
Here are the prime factors :
[7]
And any other number such as 20 :
[2, 4, 5, 10]
Here are the prime factors :
[2, 5]
will still run.
Note : I changed it from printing out just the numbers to appending the numbers to an array and then printing out the array.
Here is a one liner, you can change lower and upper limit by changing 1 and 150. Assign this to a variable. Not as fast as SoA though
[i for i in range(1,150) if all(i%j for j in range(2,int(i**(1/2))+1)) and i != 1]

Prime factorization of a number

I'm trying to write a program to find all the prime factors of a given number, and tried the following:
def factors(nr):
i = 2
factors = []
while i<nr:
if (nr%i)==0:
factors.append(i)
nr = nr/i
else:
i = i+1
return factors
My idea is the following. Start with i = 2, while i < the number, check if the module of the number and i = 0. If this is the case, add i to a list, and run the algorithm again, but now with the new number. However, my algorithm doesn't work. Any idea why?
I know that several right answers are posted on the site, but I would like to know why my program is incorrect.
Update
So if I let the programm run for example:
factors(38), yields [2].
factors(25), yields [5].
So it stops after it has added one number to the list.
The simplest change you can make to fix your problem is to change your while loop condition:
def factors(nr):
i = 2
factors = []
while i <= nr:
if (nr % i) == 0:
factors.append(i)
nr = nr / i
else:
i = i + 1
return factors
print factors(8)
print factors(9)
print factors(10)
Output
[2, 2, 2]
[3, 3]
[2, 5]
def ba(n):
pfa=[]
y=n
for i in range(n):
if (i!=0 and i!=1):
while (y%i==0):
pfa.append(i)
y=y/i
print(pfa)

Double For Loops Python

for n in range(2, 6):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n // x)
break
elif x + 1 == n:
print(n, 'is a prime number')
Result:
3 is a prime number
4 equals 2 * 2
5 is a prime number
Can anybody explain me the double for loop, why does it skip the number 2? Is it because the last number is not included in for x in range (2,2), how does this program work when iterates using 3, I tried doing the second for loop by itself using 3 and i get 2 and on another line 3, so what does it do in the third line with n%x ==0. And what does it do in the 6th line using 3? Thank you I'd appreciate it if you can walk me through this.
for n in range(2, 6):
means for n in the numbers 2 up to, but not including 6.
So, start with n = 2
The next line says
for x in range(2, n):
n is currently 2, so this means no numbers (from 2 while less than 2).
It then uses the next value for n, namely 3.
This will use range(2,3) i.e. just the number 2.
And so on.
I suggest initially just seeing what the loops do, without any code to find prime numbers.
for n in range(2, 6):
print n
for x in range(2, n):
print x
The prime number logic breaks from the loop if it finds a divisor of n

Resources