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

Given an array of digits, we need to find the smallest possible number from those digits, then check if numbers formed by the first and last digits are prime. This involves sorting digits to create the minimum number and testing primality.

Problem Overview

For example, if we have digits = [5,2,1,7], the smallest number is 1257. We then form numbers using first and last digits: 17 and 71, and check if they are prime.

Algorithm Steps

The solution follows these steps ?

  • Count frequency of each digit (0-9)
  • Build the smallest number by concatenating digits in ascending order
  • Extract first and last digits to form two numbers
  • Check primality of both numbers
  • Return results based on which numbers are prime

Prime Checking Function

First, let's implement a function to check if a number is prime ?

def isPrime(num):
    if num > 1:
        for i in range(2, int(num**0.5) + 1):
            if num % i == 0:
                return False
        return True
    return False

# Test the function
print(isPrime(17))  # True
print(isPrime(71))  # True
print(isPrime(12))  # False
True
True
False

Complete Solution

Here's the complete implementation that finds the smallest number and checks prime combinations ?

from collections import defaultdict

def isPrime(num):
    if num > 1:
        for i in range(2, int(num**0.5) + 1):
            if num % i == 0:
                return False
        return True
    return False

def solve(digits):
    # Count frequency of each digit
    digits_freq = defaultdict(int)
    for digit in digits:
        digits_freq[digit] += 1
    
    # Build smallest number by sorting digits
    number = ""
    for i in range(0, 10):
        for j in range(digits_freq[i]):
            number += str(i)
    
    # Form numbers using first and last digits
    num = int(number[0] + number[-1])  # first + last
    rev = int(number[-1] + number[0])  # last + first
    
    # Check primality and return results
    if isPrime(num) and isPrime(rev):
        return int(number), num, rev
    elif isPrime(num):
        return int(number), num
    elif isPrime(rev):
        return int(number), rev
    else:
        return False

# Test with example
digits = [5, 2, 1, 7]
result = solve(digits)
print(f"Input digits: {digits}")
print(f"Result: {result}")
Input digits: [5, 2, 1, 7]
Result: (1257, 17, 71)

How It Works

The algorithm works as follows ?

  1. Frequency Counting: Uses defaultdict to count occurrences of each digit
  2. Number Formation: Iterates through digits 0-9 and appends each digit according to its frequency
  3. Prime Testing: Forms two numbers (17 and 71) and tests both for primality
  4. Result Formation: Returns different tuples based on which combinations are prime

Testing Different Cases

# Test case 1: Both combinations are prime
digits1 = [5, 2, 1, 7]
print(f"Digits {digits1}: {solve(digits1)}")

# Test case 2: Only one combination is prime  
digits2 = [4, 2, 1, 6]
print(f"Digits {digits2}: {solve(digits2)}")

# Test case 3: Neither combination is prime
digits3 = [4, 8, 6, 9]
print(f"Digits {digits3}: {solve(digits3)}")
Digits [5, 2, 1, 7]: (1257, 17, 71)
Digits [4, 2, 1, 6]: (1246, 16)
Digits [4, 8, 6, 9]: False

Conclusion

This solution efficiently creates the smallest number from given digits and checks if the first-last and last-first digit combinations form prime numbers. The optimized prime checking function improves performance by only testing up to the square root of the number.

Updated on: 2026-03-25T14:32:03+05:30

336 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements