Problem 3: Largest Factor (100pts)
Problem
Write a function that takes an integer \(x\) that is greater than \(1\) and returns the largest integer that is smaller than \(x\) and evenly divides \(x\).
编写一个函数,接受一个大于 \(1\) 的整数 \(x\) 作为参数,并返回那个小于 \(x\) 且能整除 \(x\) 的最大整数。
def largest_factor(x):
"""Return the largest factor of x that is smaller than x.
>>> largest_factor(15) # factors are 1, 3, 5
5
>>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
40
>>> largest_factor(13) # factor is 1 since 13 is prime
1
"""
"*** YOUR CODE HERE ***"
Hints
Hint1: To check if \(b\) evenly divides \(a\), you can use the expression
a % b == 0
, which can be read as, "the remainder of dividing \(a\) by \(b\) is \(0\)."Hint2: You may want to review what is iteration?
-
要检查 \(b\) 是否能整除 \(a\),您可以使用表达式
a % b == 0
,这可以理解为:“\(a\) 除以 \(b\) 的余数是否为 \(0\)。” -
您可能需要回顾一下什么是迭代?