简体   繁体   English

乘法数字根和乘法持久性

[英]Multiplicative digital root and multiplicative persistence

I wrote the below code to figure out multiplicative digital root and multplicative persistence. 我编写了下面的代码来计算乘法数字根和乘法持久性。 I am clear about multiplicative digital root but have a question on multiplicative persistence (MP). 我很清楚乘法数字根,但有一个关于乘法持久性(MP)的问题。

In the below code, there are two while loops and to find MP have put a counter incrementing everytime the multiplication happens. 在下面的代码中,有两个while循环,并且找到MP在每次乘法发生时都将计数器递增。

MP differs when the line count += 1 was included in inner while loop and when kept in outer while loop. 当行count += 1包含在内部while循环中并且保持在外部while循环时MP不同。

Output when count += 1 is in the outer loop is 222 : [8, 3] count += 1输出在外循环中是222 : [8, 3]

Now my question is which is correct for Muliplicative persistence. 现在我的问题是多余的持久性是正确的。

Have referred https://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root and as per this count += 1 is in the outer loop and the output is 222 : [8, 1] 已经参考了https://rosettacode.org/wiki/Digital_root/Multiplicative_digital_root ,根据这个count += 1在外部循环中,输出为222 : [8, 1]

Can anyone please suggest which is one is correct? 任何人都可以建议哪一个是正确的?

    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]

for 222, the (mdr, mp) is (8, 1) . 对于222, (mdr, mp)(mdr, mp) (8, 1) -> 2*2*2 = 8 done in one loop. - > 2 * 2 * 2 = 8在一个循环中完成。

for 34, the (mdr, mp) is (2, 2) . 对于34, (mdr, mp)(2, 2) -> 3*4 = 12. 1*2 = 2. done in 2 loops. - > 3 * 4 = 12. 1 * 2 = 2.在2个循环中完成。

programmatically: 编程方式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM