'Finding prime numbers and add them to a list

I want to find all the PRIME numbers up to the given number, and add them to their lists respectively.

The number '100', has 25 primes, whereas I get 1060. What am I doing wrong?

!pip install sympy
import sympy
def count_primes(num):
    primes = 0
    nonprimes = 0
    for x in range(0, num):
        if sympy.isprime(x) == True:
            primes = primes + x
        else:
            nonprimes = nonprimes + x
    return primes    


Solution 1:[1]

instead of increasing of "primes" value by 1 you add "x" in "primes" when number is prime

Solution 2:[2]

You could this sympy.primerange() function to get a list of all prime numbers and use len() to get total number of primes for that number

def count_primes(num):
    primes = list(sympy.primerange(0, num))
    length = len(primes)
    return length

print(count_primes(100)) #25

Solution 3:[3]

The problem lies within this:

if sympy.isprime(x) == True:
        primes = primes + x
    else:
        nonprimes = nonprimes + x

Above, when you are doing primes = primes + x what you are saying is that you want to add the value of the x (a prime number) to the variable primes. Thus what is happening, when you use 100 as your num your function will return 1060, as this is the sum of all the primes up to 100.

First, if you want to know the total amount of prime numbers up to a certain number, you can use the following:

#define a variable to track the total number of primes
primeTotal = 0
#using the if statement from before
if sympy.isprime(x) == True:
    primeTotal += 1

What this does now, is for every instance of a prime number, you will add 1 to the count of prime numbers.

To create a list of prime numbers, you must first define a list, and then add the prime numbers to that list. Again, using the if statement from before:

#defining the list
primeNums = []
if sympy.isprime(x) == True:
    primeNums.append(x)

Now what is happening is, for every instance of a prime number x (the prime number) is being added (appended) to the list primeNums. This should solve both your problems.

The final bit of code will look something like this:

import sympy
def count_primes(num):
    primesTotal = 0
    primeNums = []
    for x in range(0, num):
        if sympy.isprime(x) == True:
            primesTotal += 1
            primeNums.append(x)
return primesTotal, primeNums
print(primesTotal, primeNums)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ayush maheshwari
Solution 2 gajendragarg
Solution 3 Dharman