Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you calculate the amount of prime numbers less than or equal to N?

I want to write a program that determines the amount of prime numbers less than or equal to N (variable containing user input).
This is what I’ve got:

N = int(input("Enter number: "))
count = 0
primes = []
for i in range(2, N+1):
    for j in range(2, int(i/2)+1):
        if (i % j) != 0:
            primes += [i]
            count += 1

print(count)
print(primes)

But when I run the code, it doesn’t take the numbers 2 and 3 to be prime. How can I fix this program?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can try these changes:

N = int(input("Enter number: "))
count = 0
primes = []
for i in range(2, N+1):
    is_prime = True
    for j in range(2, int(i/2)+1):
        if (i % j) == 0:
            is_prime = False
    if is_prime:
        primes += [i]
        count += 1
print(count)
print(primes)

To check if the number is prime, you need it to check if for ALL smaller numbers the remainder is different than 0.

Also, primes += [i] should be in external loop as you want to count every number at most once.

Note that this solution is far from optimal in terms of efficiency. Some improvements may be:

  • iterate j only up to math.sqrt(i)+1
  • break the inner loop as soon as you find the number is not prime
  • use Sieve of Eratosthenes
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading