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)
CodePudding user response:
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.
CodePudding user response:
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)