Count Number of Prime Numbers up to a Given Number - python

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

Related

To find a prime palindrome number

I have to print nth prime palindrome number with the help of this program, where n is number given by the user but I have a problem in this program, as it is taking much time to print the answer.
n=int(input())
l=[]
for i in range(1,1000000):
y=True
if str(i)==str(i)[::-1]:
if i>=2:
for j in range(2,i):
if i%j==0:
y=False
break
if y:
l.append(i)
print("Your Prime Palindrome Number Is:",l[n-1])
How can I make this code time efficient?
The first part of this code is not specific to this question. It's a general purpose strategy for testing prime numbers. It's faster than sympy.isprime() for values lower than ~500,000 (Python 3.11.1 on Intel Xeon) after which the sympy version betters this implementation.
from math import sqrt, floor
def isprime(n):
if n < 2:
return False
if n == 2 or n == 3:
return True
if n % 2 == 0 or n % 3 == 0:
return False
for i in range(5, floor(sqrt(n))+1, 6):
if n % i == 0 or n % (i + 2) == 0:
return False
return True
Now you need something to test for a palindrome. This function will return True if the string representation of the object is palindromic.
def ispalindrome(o):
return (_ := str(o)) == _[::-1]
And this is the main part of the program. As 2 is the only even prime number, let's treat that as a special case. Otherwise start with 3 and just test subsequent odd numbers.
N = int(input('Enter value for N: '))
if N > 0:
if N == 1:
print(2)
else:
p = 3
while True:
if isprime(p) and ispalindrome(p):
if (N := N - 1) == 1:
print(p)
break
p += 2
Sample output:
Enter value for N: 11
313

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

finding nth prime number

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.

Finding primes in python

I know that python is "slow as dirt", but i would like to make a fast and efficient program that finds primes. This is what i have:
num = 5 #Start at five, 2 and 3 are printed manually and 4 is a multiple of 2
print("2")
print("3")
def isPrime(n):
#It uses the fact that a prime (except 2 and 3) is of form 6k - 1 or 6k + 1 and looks only at divisors of this form.
i = 5
w = 2
while (i * i <= n): #You only need to check up too the square root of n
if (n % i == 0): #If n is divisable by i, it is not a prime
return False
i += w
w = 6 - w
return True #If it isnĀ“t ruled out by now, it is a prime
while True:
if ((num % 2 != 0) and (num % 3 != 0)): #save time, only run the function of numbers that are not multiples of 2 or 3
if (isPrime(num) == True):
print(num) #print the now proved prime out to the screen
num += 2 #You only need to check odd numbers
Now comes my questions:
-Does this print out ALL prime numbers?
-Does this print out any numbers that aren't primes?
-Are there more efficient ways(there probably are)?
-How far will this go(limitations of python), and are there any ways to increase upper limit?
Using python 2.7.12
Does this print out ALL prime numbers?
There are infinitely many primes, as demonstrated by Euclid around 300 BC. So the answer to that question is most likely no.
Does this print out any numbers that aren't primes?
By the looks of it, it doesn't. However, to be sure; why not write a unit test?
Are there more efficient ways(there probably are)? -How far will this go(limitations of python), and are there any ways to increase upper limit?
See Fastest way to list all primes below N or Finding the 10001st prime - how to optimize?
Checking for num % 2 != 0 even though you increment by 2 each time seems pointless.
I have found that this algorithm is faster:
primes=[]
n=3
print("2")
while True:
is_prime=True
for prime in primes:
if n % prime ==0:
is_prime=False
break
if prime*prime>n:
break
if is_prime:
primes.append(n)
print (n)
n+=2
This is very simple. The function below returns True if num is a prime, otherwise False. Here, if we find a factor, other than 1 and itself, then we early stop the iterations because the number is not a prime.
def is_this_a_prime(num):
if num < 2 : return False # primes must be greater than 1
for i in range(2,num): # for all integers between 2 and num
if(num % i == 0): # search if num has a factor other than 1 and itself
return False # if it does break, no need to search further, return False
return True # if it doesn't we reached that point, so num is a prime, return True
I tried to optimize the code a bit, and this is what I've done.Instead of running the loop for n or n/2 times, I've done it using a conditional statements.(I think it's a bit faster)
def prime(num1, num2):
import math
def_ = [2,3,5,7,11]
result = []
for i in range(num1, num2):
if i%2!=0 and i%3!=0 and i%5!=0 and i%7!=0 and i%11!=0:
x = str(math.sqrt(i)).split('.')
if int(x[1][0]) > 0:
result.append(i)
else:
continue
return def_+result if num1 < 12 else result

Python output just shows blinking cursor

I recently started messing around with python and I wrote a program to print out the 1000th prime number but the output only shows a blinking cursor , the code is shown below:
number = 3
count= 1
while count <= 1000:
prime = True
for x in range(2, number):
if number % x == 0:
prime= False
if prime == True:
count = count + 1
if count <= 1000:
number = number + 1
print number
Any help and concise explanation would be appreciated
edit: i just realized the problem. #tichodroma solved the problem but did so by editing the OP post. so when i got to it it was already solved, how ever, he solved it by putting the print into the loop, hence the many numbers waterfall. but it should be outside the loop so as to only show the final result. also - after looking at the OP code before edit, it was written in such a way that it was taking a long time to run, and the "blinking line" was the system working in the background
def isprime(n):
'''check if integer n is a prime'''
# make sure n is a positive integer
n = abs(int(n))
# 0 and 1 are not primes
if n < 2:
return False
# 2 is the only even prime number
if n == 2:
return True
# all other even numbers are not primes
if not n & 1:
return False
# range starts with 3 and only needs to go up the squareroot of n
# for all odd numbers
for x in range(3, int(n**0.5)+1, 2):
if n % x == 0:
return False
return True
counter = 0
number = 0
while True:
if isprime(number):
counter+=1
if counter == 10000:
break
number+=1
print number

Categories

Resources