-3

Correct output is: 9967

Explanation: Prime Number is any number that is divisible only by 1 and itself. Examples are 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31,........ Sum of Digits means sum of all the digits in that number. Example is number is 1234 then the sum of digits is 1+2+3+4=10

def sumofprime(x):
    con1,con2=False,False 
    for num in range(x,1000,-1):
        for i in range(2, num):
            if (num % i) == 0:
                break
            else:
                print(num)
                con1=True
                break
    sum=0
    while(num>0):
        dig=num%10
        sum=sum+dig
        num=num//10
    print(sum)
    
    
    x=sum
    for i in range(2, x):
        if (x % i) == 0:
            print(x, "is not a prime number") 
            break
        else:
            print(x, "is a prime number")
            con2=True
        
        
    if con1==True and con2==True:
        print(num,sum)
        break
    else:
        sumofprime(x-1)
        


sumofprime(9999)

1 Answers1

0

You can not use a break outside of a loop. Your code looks overly complicated and long. You should use the "divide and conquer" strategy to solve your problems:

List of problems:

  1. Generate primes below n
  2. from that get all primes that got a digit sum thats also prime
  3. get maximum of those primes and print it

Generate all needed primes':

def primes(n):
    """Credit:   https://stackoverflow.com/a/3035188/7505395"""
    sieve = [True] * n
    for i in range(3, int(n ** 0.5) + 1, 2):      
        if sieve[i]:          
            sieve[i * i :: 2 * i] = [False] * ((n - i * i - 1) // (2 * i) + 1)
    return {2} | {i for i in range(3, n, 2) if sieve[i]}

Extract primes that got a prime-digit-sum:

def sumofprime(x): # python 3.8+, less complicated variant for up to 3.7 further down
  ps = primes(x)
  return ((p,su) for p in sorted(ps) if ((su := sum(map(int,str(p)))) != p and su in ps))

Get maximum prime and print:

all_primes_with_sums_below_10000 = list(sumofprime(10000))

answer = "Prime {} internal digit sum is {} and also prime."
print(answer.format(*max(all_primes_with_sums_below_10000)) )

Output:

Prime 9967 internal digit sum is 31 and also prime.

You can translate

def sumofprime(x):
  ps = primes(x)
  return ((p,su) for p in sorted(ps) if ((su := sum(map(int,str(p)))) != p and su in ps))

into a loop that works with python before 3.8 like so:

def sumofprime(x): # python before 3.8
  # get all primes
  ps = primes(x)
  rv = []
  # lets use sorted for some orderly printing if you print them all
  for p in sorted(ps):
     # get the inner sum
     su = sum(map(int,str(p)))
     # 2=2 and 5=5 etc are boring, also only interested in sums that are primes
     if su != p and su in ps:
         rv.append( (p,su) ) 
  return rv
Patrick Artner
  • 43,256
  • 8
  • 36
  • 57