-1

I need to find the total of prime numbers less than or equal to a given natural number. Ex, with natural number (n) = 4, than the total = 2 +3 = 5.

I wrote the below codes to solve the problem and it seems to be correct until n = 4, however, when n > 4, it starts appearing the repetitive result of eligible f. Eg. when n = 5, f = 3,5,5,5 => total of prime = 20.

Could you explain what is wrong with my codes and how to fix it?

n = eval(input("Input n (natural number): "))
e = 0
if n == 1:
    e = 0 
else:
    f = 3
    e = 2
    while f <= n:
        for r in range(2,f):
            if f %r == 0:
                break
            else:
                e += f
        f +=1
print("Total of prime = ",e )
Community
  • 1
  • 1
ND97
  • 31
  • 1
  • Hope this one helps: https://www.geeksforgeeks.org/print-all-prime-numbers-less-than-or-equal-to-n/ – srishtigarg Jan 01 '21 at 09:42
  • 1
    How often do you expect `else: e += f` to happen? – jonrsharpe Jan 01 '21 at 09:43
  • You can do this in two parts: - find primes inferior to given number n : duplicate of here: https://stackoverflow.com/questions/3939660/sieve-of-eratosthenes-finding-primes-python - do the sum of all the result. Easy to do with the reduce(..) method. – Malo Jan 01 '21 at 10:21
  • 1
    @srishtigarg Thank you for sharing other ways to complete the tasks. It does help. – ND97 Jan 01 '21 at 12:24
  • @jonrsharpe: got it! I did not put else: e +=f in the right position. Thank you and happy new year. – ND97 Jan 01 '21 at 12:29

1 Answers1

1

As I understand it you add 'f' too many times to the total.

'f' should be added only if f%r is never 0 for a given f. In your code you add f eachtime f%r is different than 0 for each test, and each value of r.

Here is a modified and working version: Just place the 'else' part after the for loop, not inside: This means the f will be added only once if it is not dividable, so only if f is prime.

n = eval(input("Input n (natural number): "))
e = 0
if n == 1:
    e = 0 
else:
    f = 3
    e = 2
    while f <= n:
        for r in range(2,f):
            if f %r == 0:
                break
        else:
            e += f
        f +=1
print("Total of prime = ",e )

Example outputs:

Input n (natural number): 5
Total of prime =  10

or

Input n (natural number): 8
Total of prime =  17
Malo
  • 1,233
  • 1
  • 8
  • 25
  • Hi Malo, thank you so much for your help. I see the problem and the codes are working now. Thanks again and Happy new year!! – ND97 Jan 01 '21 at 12:17
  • Hi @ND97, you're welcome, please upvote and/or select the answer if it is good for you. Happy New year! – Malo Jan 01 '21 at 12:22