Python program to find better divisor of a number

PythonServer Side ProgrammingProgramming

Suppose we have a number n. We have to find divisor of n which one is better based on these conditions: We have two numbers p and q, the one whose digits sum to a larger number is called better than the other one. When the sum of digits is same, then the smaller number is the better one.

So, if the input is like n = 180, then the output will be 9 because the divisors are [1, 2, 3, 4, 5, 6, 9, 10, 12, 15, 18, 20, 30, 36, 45, 60, 90, 180]. So the number whose digit sums are maximum are [9, 18, 36, 45, 90, 180], but among them 9 is better number as its value is smaller.

To solve this, we will follow these steps −

  • div := 1, md := 1
  • for i in range 2 to n, do
    • k := i
    • if n mod i > 0, then
      • go for next iteration
    • s := 0
    • while k > 0, do
      • s := s + k mod 10
      • k := k / 10
    • if s > md, then
      • md := s
      • div := i
  • return div

Example

Let us see the following implementation to get better understanding

def solve(n):
   div = 1
   md = 1
   for i in range(2, n + 1):
      k = i
      if n % i > 0:
         continue
      s = 0
      while k > 0:
         s += k % 10
         k /= 10
      if s > md:
         md = s
         div = i

   return div

n = 180
print(solve(n))

Input

180

Output

9
raja
Updated on 12-Oct-2021 07:33:33

Advertisements