finding nth prime number - python

I've written a code block to find n-th prime number.
For instance if n=2, then the result is 3 and if n=3, then 5 and so on.
Below is my code.
def prime_or_not(n):
for i in range(2, int(n ** 0.5)+1):
if n % i == 0:
return False
else:
return True
def get_first_n_prime(n):
while True:
if prime_or_not(n):
yield n
n += 1
def get_nth_prime_number(n, initial_number=2):
count = 0
for next_prime in get_first_n_prime(initial_number):
count += 1
if count < n:
continue
else:
return next_prime
With the code above, I could get expected result.
The question, however, is that I'm not sure whether this is pythonic way of using generator (with yield in a function). Any feedback or comment would be immensely helpful.

Related

Count Number of Prime Numbers up to a Given Number

I'm currently trying to create a function to count the number of prime numbers up till a given number. However, I think I have some issues with the logic of my code as I'm currently not getting back the right number of prime numbers. Could anyone help me identify what's wrong with my code? Thanks!
def count_primes(num):
ctr = 0
for i in range(num+1):
for x in range(2,i):
if (i%x) != 0:
ctr += 1
break
else:
break
return ctr
print(count_primes(10))
#I get 4
print(count_primes(100))
#I get 49
The problem with the logic is as follows - for every number you just check if it is divisible by 2 and break. Let's simulate for i=9. Then for x=2, (9 %2)!=0 but 9 is not prime but is counted as one. Check the following code -
def isPrime(n):
if not isinstance(n, int):
raise ValueError('n must be integer')
if n <= 0:
raise ValueError('n is negative or zero')
if n==1: return False
for i in range(2, n):
if n % i == 0:
return False
return True
def countPrime(n):
ctr = 0
for i in range(1, n+1):
if isPrime(i):
ctr += 1
return ctr
Disclaimer - there are more efficient ways to check if a number is prime

Find the next prime number in Python

I have a function that takes a number (for example, 5) and returns the first prime number after the input number (in this case, it would be 7).
This is my code:
def prime(n):
np=[]
isprime=[]
for i in range (n+1,n+200):
np.append(i)
for x in range(2,199):
for j in np:
if x%j!=0:
isprime.append(x)
return min(isprime)
However, this code doesn't work (it always returns 2). Where is the mistake?
You have a few mistakes, most notably np is clearly meant to be the potential primes (it starts at n+1 which is the first potential number that fits your critera "the first prime number after the input number"), and yet you add x to your prime list, which is from range(2,199), you should be using:
isprime.append(j)
Your primality test is also the wrong way round as a result, you should be using:
j % x != 0
Lastly, you can't append a number if that condition is true in one case, it has to be true in all cases (where x is an integer which satisfies 2 <= x < j), because of this you should switch your second set of for loops around (the x loop should be the inner loop), and you should also only loop up to j-1 (the number being tested). Additionally, you should instead choose to not add an item if j % x == 0:
for ...:
val_is_prime = True
for ...:
if j % x == 0:
val_is_prime = False
break
if val_is_prime:
isprime.append(j)
This results in the following code:
def prime(n):
np=[]
isprime=[]
for i in range (n+1,n+200):
np.append(i)
for j in np:
val_is_prime = True
for x in range(2,j-1):
if j % x == 0:
val_is_prime = False
break
if val_is_prime:
isprime.append(j)
return min(isprime)
And test run:
>>> prime(5)
7
>>> prime(13)
17
>>> prime(23)
29
Note that there's several other efficiency improvements that could be made, but this answer focuses on the mistakes rather than improvements
Try this one, the most pythonic and clear way to do this that I found (but probably not the most efficient):
def is_prime(x):
return all(x % i for i in range(2, x))
def next_prime(x):
return min([a for a in range(x+1, 2*x) if is_prime(a)])
print(next_prime(9))
https://www.geeksforgeeks.org/python-simpy-nextprime-method/
from sympy import *
# calling nextprime function on differnet numbers
nextprime(7)
nextprime(13)
nextprime(2)
Output:
11 17 3
This code working.
def prime(n):
next_prime = n + 1
prime = True
while True:
for i in range(2, next_prime):
if next_prime%i ==0:
prime = False
break
if prime:
return next_prime
else:
next_prime = next_prime + 1
if next_prime % 2 == 0:
next_prime = next_prime + 1
prime = True
if __name__=="__main__":
print(prime(5))
Here is one working sample.
inputNumber = int(input("Enter number to find next prime: "))
def nextPrime(inputNum):
for nextNumToChk in range(inputNum+1, inputNum +200):
if nextNumToChk > 1:
# If num is divisible by any number between 2 and val, it is not prime
for i in range(2, nextNumToChk):
if (nextNumToChk % i) == 0:
break
else:
#found the prime
return nextNumToChk
result = nextPrime(inputNumber)
print "Next Prime is : ",result
Output:-
Enter number to find next prime: 5
Next Prime is : 7
def is_prime(n):
# Corner case
if n <= 1:
return False
# Check from 2 to n-1
for i in range(2, n):
if n % i == 0:
return False
return True
def first_prime_over(n):
prime_number = (i for i in range(n) if is_prime(i))
try:
for i in range(0,n):
(next(prime_number))
except StopIteration:
prime_number_next = (i for i in range(n,n+1000) if is_prime(i))
print(next(prime_number_next))
first_prime_over(10)
Try this one:
def find_next_prime(n):
return find_prime_in_range(n, 2*n)
def find_prime_in_range(a, b):
for c in range(a, b):
for i in range(2, c):
if c % i == 0:
break
else:
return c
return None
def main():
n = int(input('Find the next prime number from: '))
print(find_next_prime(n+1))
if __name__ == '__main__':
main()
n = int(input("Enter a number"))
while True:
n+=1
for x in range(2,n):
if n%x==0:
break
else:
print("next prime number is",n)
break

Count prime results of polynomial

Can someone help me and tell me why this doesn't work? The goal is to count the number of prime numbers that are produced by a given polynomial for inputs n in a specified range [a,b]:
def count_primes(poly, a, b):
primes = 0
if b >= a:
for n in range(a, b):
result = poly(n)
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
else:
break
return primes
def poly(n):
return n**2 + n + 41
print(count_primes(poly, 0, 39))
The result should return 40 in this case.
[2] Problem Solution
Step-1. Take in the number to be checked and store it in a variable.
Step-2. Initialize the count variable to 0.
Step-3. Let the for loop range from 2 to half of the number (excluding 1 and the number itself).
Step-4. Then find the number of divisors using the if statement and increment the count variable each time.
Step-5. If the number of divisors is lesser than or equal to 0, the number is prime.
Step-6. Print the final result.
Step-7. Exit.
The problem is that the else clause in the nested loop refers to the if, when it should be activated only if the loop finished without break. Just change the identitation to:
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
This is the wrong way to count primes:
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
Should be:
if result > 1:
isPrime = True
for i in range(2, result):
if (result % i) == 0:
isPrime = False
break
if isPrime:
primes += 1
Also, it goes without saying. Easy optimizations for prime number detection. You only have to test for divisibility divisibility with 2 and all odd numbers between 3 and sqrt(result).
def count_primes(poly, a, b):
primes = 0
if b >= a:
for n in range(a, b+1):
result = poly(n)
if result > 1:
for i in range(2, result):
if (result % i) == 0:
break
else:
primes += 1
else:
break
return primes
def poly(n):
return n**2 + n + 41
print(count_primes(poly, 0, 39))
Problems:
you do primes += 1 too early. In your methods, you have to test until no possible division happens, then do the addition.
[a, b] The endpoints are both inclusive. Then you should use b+1 at your for n in range(a, b+1), which produces 40.

Python print non-prime numbers

I have a hackkerank coding challenge to print first n non prime numbers, i have the working code but the problem is that they have a locked code which prints numbers from 1 to n along with the output, in order to pass the test i need to print only the non prime numbers not 1...n numbers along with it. I cant comment the printing part of 1...n as it is blocked. please let me know the idea to print only 1st n non prime numbers:
here is my solution:
def manipulate_generator(generator, n):
if n>1:
ls=[1]
for elm in generator:
if elm>3 and len(ls)<n:
for k in range(2,elm):
if elm%k==0 and elm not in ls:
ls.append(elm)
print(elm)
if len(ls)==n:
return ls
That's the code I added but here is the code that's locked on which I have to write the code above to make it print the number one at a time
def positive_integers_generator():
n = 1
while True:
x = yield n
if x is not None:
n = x
else:
n += 1
k = int(input())
g = positive_integers_generator()
for _ in range(k):
n = next(g)
print(n)
manipulate_generator(g, n)
the point is the for _ in range(k): already prints out number which includes numbers I don't want printed out: This is the desired kind of output I want:for n=10 I want it to print out:
output:
1
4
6
8
9
10
12
14
15
16
I can't change this code but the one above is what I wrote and can be changed... Pleae help me out... Thanks in anticipation
Why not to throw away the numbers which we don't need? Look at this solution which I implemented...
def is_prime(n):
for i in range(2, n):
if n%i == 0:
return False
return True
def manipulate_generator(generator, n):
if is_prime(n+1):
next(generator)
manipulate_generator(generator, n+1)
Note: I understand that the logic can be improved to make it more efficient. But, its the idea of skipping unnecessary number printing which is important here !
You can print all the numbers from 1 up to the first prime number and then from that first number to the next one until you reach n.
I'm not sure of your hackerrank situation, but printing the first N non-prime numbers efficiently can be done this way.
def non_prime_numbers_till_n(n):
primes = set()
for num in range(2,number + 1):
if num > 1:
for i in range(2, math.sqrt(num)):
if (num % i) == 0:
break
else:
primes.add(num)
result = []
for i in range(1, n):
if i not in primes:
result.append(i)
return result
Depending on what your online editor expects you can either print them, or store them in a list and return the list.
Also bear in mind, you can only check upto the sqrt of the number to determine if its a prime or not.
I eventually came up with this answer which I believe should solve it but id there;s a better way to solve it please add your answers:
def manipulate_generator(generator, n):
for num in range(3,100000):
for q in range(2,num):
if num%q==0 and num>n:
generator.send(num-1)
return
this link python generator helped me to understand python generator
I just solved that right now. Like Swapnil Godse said you need to deal with all special cases to optimize computations. This link might be helpful: click here.
Here is the solution:
from math import sqrt
def is_prime(n):
if (n <= 1):
return False
if (n == 2):
return True
if (n % 2 == 0):
return False
i = 3
while i <= sqrt(n):
if n % i == 0:
return False
i = i + 2
return True
def manipulate_generator(g, n):
if is_prime(n+1):
next(g)
manipulate_generator(g, n+1)
prime = int(input('Please enter the range: '))
prime_number = []
for num in range(prime):
if num > 1:
for i in range(2,num):
if num % i == 0:
break
else:
prime_number.append(num)
print(f'Prime numbers in range {prime} is {prime_number}')
all_number = []
for i in range(2,prime+1):
all_number.append(i)
Non_prime_number = []
for element in all_number:
if element not in prime_number:
Non_prime_number.append(element)
print(f'Non Prime numbers in range {prime} is {Non_prime_number}')

Python algorithms nth prime number

Question:
Given the prime number n, output the number of prime numbers
My code:
def kthPrime(self, n):
if n>10 and n%10 not in [1,3,7,9]:
return 0
if n == 2:
return 1
queue = []
num = 2
while num <= n:
if n%num == 0 and num != n:
return 0
if num>10 and num%10 not in [1,3,7,9]:
num += 1
continue
for i in range(2,num/2+1):
if num%i == 0:
num += 1
break
else:
queue.append(num)
num += 1
seq = queue.index(n) + 1
return seq
Error:
Your code ran too much time than we expected. Check your time complexity. Time limit exceeded usually caused by infinite loop if your time complexity is the best.
My Question: how to improve it
as user #Prune said , please read the guide first.
I'm not going to tell you how to improve your function , but I'm just gonna give you a faster way to see whether a number is prime or not and hopefully you will understand how to use the function that I'm gonna give you to improve your own function.
The source code :
class numChecker:
def is_prime(self,n):
if n == 2:
return True
if n % 2 == 0 or n < 2:
return False
self.square_root = int(n ** (1/2))
for divisor in range(3, self.square_root + 1, +2):
if n % divisor == 0:
return False
return True

Categories

Resources