pythonnumbersreorderlist

Reorder number N to become the largest number divisble by M


Suppose I have the number N, with 1 <= N <= 10^15. I want to reorder the number so that you get the largest number possible and it is divisible by M.( M is any even number less than 12)

E.g: N = 4264, M = 8 then the largest number divisible by M made by the digits of N is 6424

This is my code:

n = int(input())
m = int(input())
s = list(map(int,list(str(n))))
s.sort(reverse=True)
# missing part here
print("".join(map(str, s)))

I am missing the part to reorder the digits of N. Can someone help me?


Solution

  • You simply need to define a function to check the divisibility of a number by a given integer:

    import itertools
    
    def smallest_divisible_by_m(digits, m):
        digits.sort()
        for perm in itertools.permutations(digits):
            if perm[0] == 0:
                continue
            num = int(''.join(map(str, perm)))
            if num % m == 0:
                return num
        return None  
    n = int(input("Enter N: "))
    m = int(input("Enter M: "))
    
    digits = list(map(int, str(n)))
    
    result = smallest_divisible_by_m(digits, m)
    if result is not None:
        print("The smallest number formed by the digits of", n, "that is divisible by", m, "is", result)
    else:
        print("No valid number formed by the digits of", n, "is divisible by", m)
    
    

    Here is the output of your example:

    enter image description here