Check if the first and last digit of the smallest number forms a prime in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array called digits that contains only digits. We have to find the minimum possible number from the given digits and then check whether the numbers by taking first and last digits of the generated number are prime or not. We will print the number itself and then the prime numbers.

So, if the input is like digits = [5,2,1,7], then the output will be 1257 is the smallest number. The numbers by taking first and last digits are 17 and 71, both are prime.

To solve this, we will follow these steps −

  • digits_freq := a map containing frequencies of digits
  • number := blank string
  • for i in range 0 to 9, do
    • for j in range 0 to digits_freq[i] - 1, do
      • number := number concatenate digit i
  • num := number by taking first and last digit of number
  • rev := number by taking last and first digit of number
  • if num is prime and rev is prime, then
    • return number, num, rev
  • otherwise when num is prime, then
    • return number, num
  • otherwise when rev is prime, then
    • return number, rev
  • otherwise,
    • return False

Let us see the following implementation to get better understanding −

Example Code

Live Demo

from collections import defaultdict
 
def isPrime(num):
   if num > 1:
      for i in range(2, num):
         if num % i == 0:
           return False
      return True
   return False
 
def solve(arr):
   digits_freq = defaultdict(int)

   for i in range(len(arr)):
      digits_freq[arr[i]] += 1
 
   number = ""
   for i in range(0, 10):
      for j in range(digits_freq[i]):
         number += str(i)
       
   num = int(number[0] + number[-1])
   rev = int(number[-1] + number[0])
 
   if isPrime(num) and isPrime(rev):
      return int(number), num, rev
   elif isPrime(num):
      return number, num
   elif isPrime(rev):
      return number, rev
   else:
      return False
   
digits = [5,2,1,7]
print(solve(digits))

Input

[5,2,1,7]

Output

(1257, 17, 71)
raja
Published on 15-Jan-2021 06:38:08
Advertisements