Check numbers in a list and tell if they can be expressed as the sum of two prime numbers

Asked

Viewed 39 times

0

The code below checks whether a given integer can be expressed by the sum of two primes:

def sum_of_primes(num):
  isPrime = 1
  for i in range (2,int(num/2),1):
    if(num % i == 0):
        isPrime = 0
        break
  return isPrime

num = int(input("Enter a number : "))

flag = 0
i = 2
for i in range (2,int(num/2),1):
  if(sum_of_primes(i) == 1):
    if(sum_of_primes(num-i) == 1):
        print(num,"pode ser expresso como a soma de",i,"e",num-i)
        flag = 1;
if (flag == 0):
  print(num,"não pode ser expresso como a soma de dois primos")

the code works correctly (except when I enter the number 5. It says that it cannot be formed by the sum of two primes but we know that it can: 2+3. I haven’t figured out why).

What I need to do is adapt the code so that it receives a list of numbers and does this check in the typed list. I used the following input:

num = [int(n) for n in input("Digite os número: ").split()]

However I did not get the expected result, IE, the program does not check for all items of the typed list.

Can someone help me?

  • 3

    range(2,int(num/2),1) - when num is 5, int(num / 2) is 2, so you created a range(2,2,1), only in a range the final value is not included, so it does not even enter the for. Just switch to range(2,int(num/2) + 1) - note also that you do not need the third parameter, because its default value is already 1

  • 1

    The famous Goldbach conjecture says that every PAR number greater than 3 equals the sum of two prime numbers.

  • perfect with respect to the range: now works with the 5.

  • Now I just need to be able to do the same check when the user type a list instead of a single number.

  • 1

    If you already have a function that verifies that a certain number can be formed by two primes, then you can do another function that scrolls through the numbers in the list and calls the function to verify sum of primes one by one.

  • The body of this new function can be something as trivial as all(is_sum_of_primes(n) for n in lista)

Show 1 more comment
No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.