当前位置:网站首页>Number of detection cycles "142857“

Number of detection cycles "142857“

2022-06-13 07:05:00 Flying bird immortal

describe
If one n The string of digits satisfies the following conditions , It is called a cyclic number (cyclic): Treat this string of numbers as an integer ( May have a leading 0), And use any one 1 To n Between ( contain 1 and n) When you multiply it by an integer of , You will get a string that connects the beginning and end of the original string , The integer corresponding to the new number string obtained by disconnecting at some place . for example , Numbers 142857 It's the number of cycles , because :
142857 *1 = 142857
142857 *2 = 285714
142857 *3 = 428571
142857 *4 = 571428
142857 *5 = 714285
142857 *6 = 857142.

Please write a program to judge whether a given number is a circular number .

Be careful : In this question , The input string can be preceded 0, And leading 0 Can't be ignored , for example “01” Is a two digit string , and “1” Is a string of digits . But when converting a number string to an integer for multiplication or comparison , You can ignore the leading 0.
 

python The advantage is that it supports large number calculation , If it is C++ You need to write your own functions to add, subtract, multiply and divide large numbers ;

Ideas :

1) Write a function to verify , Whether two numbers are the same after being shifted ; The cycle of violence is used here to compare ;

2) Write a function to do 2 ~ len(s) Multiplication of , Each multiplication result is converted to a string , And use 0 Prefix complement length ; Compare whether it is the same after shifting ;

# 0 <= n <= len(s)
def numShift(s, n):
    d = s[n:] + s[:n]
    return d

# check string is same with s1, 
def checkSame(s, s1):
    #print("-----------------check same----------------")
    for i in range(1, len(s)):
        d = numShift(s, i)
        #print("%d, %s" % (i, d))
        if (s1 == d):
            return True

    return False


# check cycle num with multi by [2... len(num)]
def checkNum(num):
    for i in range(2, len(num)+1):
        newNum = int(num) * i

        num1 = str(newNum).zfill(len(num)) #  Front completion 0
        print("%s * %d = %s" % (num, i, num1) )

        if False == checkSame(num, num1):
            return False
 
    return True

b = checkNum("253968")
#b = checkNum("142857")
#b = checkSame("142857", "714285")
print(b)

原网站

版权声明
本文为[Flying bird immortal]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/164/202206130656320284.html