Python, trying to sum prime numbers, why is '7' not getting appended?

Viewed 44

I am trying to make a simple function to sum the prime numbers of a given input. I am wondering why '7' isn't coming up in my appended list of prime numberS:

def sum_primes(n):
    empty = []
    for i in range(2,n):
        if n % i == 0:
            empty.append(i)
    print(empty)

sum_primes(10)
4 Answers

Your method for determining if numbers are prime is a bit off. Your function seems to determine if the input num n is prime but not sum all prime numbers to it.

You could make an isprime function and then loop over that for all numbers less than n to find all primes.

Actually your program have logical error. First you have to understand the prime number logic.

Step 1: We must iterate through each number up to the specified number in order to get the sum of prime numbers up to N.

Step 2: Next, we determine whether the given integer is a prime or not. If it is a prime number, we can add it and keep it in a temporary variable.

Step 3: Now that the outer loop has finished, we can print the temporary variable to obtain the total of primes.

sum = 0
for number in range(2, Last_number + 1):
    i = 2
    for i in range(2, number):
        if (int(number % i) == 0):
            i = number
            break;
    if i is not number:
        sum = sum + number

print(sum)
def sum_primes(y):
    sum = 0

    # for each number in the range to the given number
    for i in range(2, y):
        # check each number in the sub range
        for j in range(2, int(i/2)+1):
            # and if its divisble by any number between
            # 2 and i/2
            if i % j == 0:
                # then it is not a prime number
                break
        else:
            # print current prime
            print(i)
            # add prime to grand total
            sum += i
    return sum

print(sum_primes(10))

I think you have some problems with the way you are checking if your number is prime or not. A much simpler way would be to use a library that does this for you. It takes less time, is usually a better implementation than you or I could come up with, and it takes fewer lines, therefore, looking cleaner.

I would recommend primePy. Its whole point is to work with prime numbers.

I don't have my computer with me atm so I can't make any sample code for you and test it. But something like this should work.

from primePy import primes
prime_list = primes.upto(n)
print(prime_list)

I believe that function returns a list of all prime numbers up to n. And if you wanted to get the sum of all of those numbers, you can go about whatever method you want to do that.

Afterward, slap it into a def and you should be good to go.

If it doesn't work let me know, and I will try to test and fix it when I am in front of a computer next.

Related