简体   繁体   中英

Finding sum of prime digits in python

So I wrote a program that calculates the sum of all prime digits in a number.

#python program to print the sum of prime digits
number = int(input("Enter a number"))
n = number
number_of_digits = 0
is_prime = True
total = 0
while n>0:
    number_of_digits+=1
    n = int(n/10)
for i in range(1, number_of_digits+1):
    for j in range(2, int(number%10)):
        if int(int(number%10)%j)==0:
            is_prime = False
            break
    if is_prime == True:
        total = int(number%10)
    is_prime = True
    number = int(number/10)
print(total)

But it doesn't work. It is a logical error, but I can't figure it out. I didn't find answers to this question here, and I don't want to see solutions as I want to know what's the mistake on my side.

1 is not a prime. You should consider this in

if int(int(number%10)%j)==0:

A small mistake: total += int(number%10)

Don't use

if is_prime == True:

Please use

if is_prime:

to make your code more pythonic.

Since prime digits are known in advance, it's easier to iterate through each digit of the number and add the prime number digits

number = input("Enter a number")
prime_digits={'2','3','5','7'}
sum_ = 0

for digit in number:
    if digit in prime_digits:
        sum_+= int(digit)
print('sum of prime digits: ',sum_)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM