首页 > 解决方案 > How can I make the largest number with most numbers of divisors appear in the output?

问题描述

Title kinda says it all, how do I make a code where I can make the largest number with most divisors appear in the output?

start = int(input("Enter start number: "))

     if start <= 0:
        print("Invalid Input...")

end = int(input("Enter end number: "))

     if end <= 0:

        print("Invalid Input...")

divisor = 0

for i in range (start, end):

     if end% i == 0:
        divisor = i
        divisor //= start

print("{0} has {1} divisor.".format(end, divisor))

I expect the output to be like if I input 5 at start and 100 at the end it would look like

Enter start number: 5

Enter end number: 100

96 has 10 divisors.

But instead of 96 it is 100.

标签: python-3.x

解决方案


制作一个函数,它将返回所选数字的除数。这样你就可以找到一个具有最大除数的数字并打印它:

start = int(input("Enter start number: "))

if start <= 0:
    print("Invalid Input...")

end = int(input("Enter end number: "))

if end <= 0:
    print("Invalid Input...")

def divisors(n):
    cnt = 0
    for i in range(2,int(n**0.5)+1):
        if n%i == 0:
            cnt += 2
    return cnt

current_max, current_cnt = 0, 0
for i in range(start, end):
    n = divisors(i)
    if n >= current_cnt:
        current_cnt = n
        current_max = i

print("{0} has {1} divisor.".format(current_max, current_cnt))

打印(用于输入5100):

96 has 10 divisor.

推荐阅读