为什么使用 math.fmod 与 mod 运算符会得到不同的答案仅限正整数

问题描述

试图找到最小的正整数 n 使得 n!除以 n! 的数字之和!有余数。

两个人以相似的方式解决了这个问题,但得到了不同的答案。我读过 % 和 fmod 对负数的行为不同,但这里不涉及负数。网上的大量计算器似乎表明,通过 % 得出的解决方案是正确的。

使用 mod 运算符:

import math
n=1
def func():
    global n
    intn=[]
    
#for loop creates a list of integers of the digits of n!
    for digit in str(math.factorial(n)):
         intn.append(int(digit))
    denominator=sum(intn)
    
#if n!/denominator has a remainder,print n; the program is over. Otherwise,increase n and try again.
    if (math.factorial(n))%denominator:
        print(n)
    else:
        n+=1
        func()
func()

if (math.factorial(n))%(denominator): 更改为 if int((math.factorial(n)))%int(denominator): 更改了结果,使其与使用 .fmod 时的结果相同,但同样,我认为这不是正确答案。

使用 math.fmod:

import math

# curNum is the variable I'm using to track the integer whose value I'm testing
curNum = 1

# conditionMet is a boolean that will be used to break the while loop of the test
conditionMet = False


while conditionMet == False:
    sumDigits = 0
    curFactorial = math.factorial(curNum)
    curFactorialAsstring = str(curFactorial)
    #sumDigits  = sum(int(curNumAsstring))
    for curDigit in curFactorialAsstring:
            sumDigits = sumDigits + int(curDigit)
    if math.fmod(curFactorial,sumDigits) != 0:
        print("curNum: " + str(curNum) + "curFactorial: " + str(curFactorial) + "sumDigits: " + str(sumDigits))
        conditionMet = true
    else:
        curNum = curNum + 1

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)