Get the closest prime number with python

In this chapter, we will create a method which will return the value which needs to be added to the total of all the numbers within a list to get the closest prime number from that total. A prime number is a number which can only be divided by one and itself. 1 is not a prime number. The below program will add one to the sum of all the numbers within a list until it reaches the closest prime number from that total, it then will return the value which needs to be added to reach that prime status.

def minimum_number(numbers):
    
    total = sum(numbers)
    n=0
    notprime = True

    if(total == 1):
        return 1
    elif(total == 2):
        return 0
    else:
        while(notprime):
           
            for i in range(2,total):
            
                if(total%i == 0):
                    notprime = True
                    break
                else:
                    notprime = False
                    
            if(notprime == True):
                total+=1
                n+=1
            else:
                return n

As you can see we will use the notprime flag to control the while loop until we get the answer which we need. Like, share or comment on this post, if you have nothing to do then why not donate some cryptocurrencies through the donation widget (on the sidebar of this website) to help funding this site, thank you for your help.

Leave a Reply

avatar
  Subscribe  
Notify of