我写了下面的代码来找出乘法的数字根和乘法的持久性。我对乘法数字根很清楚,但对乘法持久性(MP)有疑问。
在下面的代码中,有两个while循环,并且为了发现MP每次累加时都会增加一个计数器。
当内部count += 1
行包含在内部while循环中并且保留在外部while循环中时,MP有所不同。
count += 1
在外部循环中时的输出为222 : [8, 3]
现在我的问题是对于多重复制持久性是正确的。
已引用https://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root,并且根据此count += 1
在外部循环中,输出为222 : [8, 1]
任何人都可以建议哪个是正确的吗?
def mdr_mp(num):
'''
This function computes the multiplicative digital root and multiplicative persistence of a given number
'''
product = 1
mdr = num
count = 0
#Find mdr and persistence
while mdr > 9: #as long as mdr is > 9
while num > 0: #as long as quotient is > 0
#use divmod fn to return the quotient and remainder of num when divided by 10
num, number = divmod(num, 10)
product *= number #perform product of each digit in the number
count += 1
mdr = product #set product to mdr so as to check if it is > 9 else repeat
num = product #set product to num so as to perform the product again
product = 1 #initialize product to 1 so that product of the new num can be computed
#count += 1 #multiplicative persistence
return [mdr, count] #returns multiplicative digital root and multiplicative persistence as a list
num = 222
#Function call returns list of number containing mdr and mp
print("Number: (MDR, MP)")
list1 = mdr_mp(num)
print(num, ": ", list1)
Output:
Number: (MDR, MP)
222 : [8, 3]
答案 0 :(得分:0)
对于222,(mdr, mp)
是(8, 1)
。 -> 2 * 2 * 2 = 8个循环。
对于34,(mdr, mp)
是(2, 2)
。 -> 3 * 4 =12。1* 2 =2。在2个循环中完成。
以编程方式:
def get_mdr_and_mp(number):
time_multiplied = 0
current_mdr = number
while current_mdr > 9:
current_mdr = multiply_all_digits(current_mdr)
times_multiplied += 1
return current_mdr, times_multiplied
答案 1 :(得分:0)
这里是另一种简化的代码形式:
def mula(a):
mul=1
for i in str(a):
mul=mul*int(i)
mul+=1
return (mul-1)
c=int(input("Enter a number"))
cnt=0
while c>=10:
c=mula(c)
cnt+=1
print("MDR:{} MPer:{}".format(c,cnt))