什么是循环数?Python 一行代码判断循环数

阿里云-轻量应用服务器

循环数英语:cyclic number)是一类特殊的整数,其包含的各个数字的循环排列恰为该数的连续倍数 ; 一个n位的循环数的性质是它乘以1至n都是各个数字的循环排列 , 乘以(n+1)会出现纯位数 , 纯位数每个位都是9。例如,最知名的循环数是142857

142857 × 1 = 142857
142857 × 2 = 285714
142857 × 3 = 428571
142857 × 4 = 571428
142857 × 5 = 714285
142857 × 6 = 857142

乘以7出现纯位数

142857 × 7 = 999999

长度为L的循环数可以表示为单位分数 小数表示形式的循环部分。反过来,如果 (其中p素数)的循环长度为p-1(这样的素数p称为全循环素数),那么其循环部分表示的就是一个循环数。例如: 

其不同倍数的循环部分则是该循环数的循环排列:

Python 一行代码判断循环数(86个字母):

lambda n:all(sorted(n)==sorted(str(int(n)*i).zfill(len(n)))for i in range(2,len(n)+1))

Python 3.0 判断循环数:

# Program to check if
# a number is cyclic
# Function to generate
# all cyclic permutations
# of a number
def isCyclic(N):

# Count digits and check if all
# digits are same
num = N
count = 0
digit =(num % 10)
allSame = True

while (num>0):
count+= 1
if (num % 10 != digit):
allSame = False
num = num // 10

# If all digits are same, then
# not considered cyclic.
if (allSame == True):
return False

# If counts of digits is even and
# two halves are same, then the
# number is not considered cyclic.
if (count % 2 == 0):

halfPower = pow(10, count//2)
firstHalf = N % halfPower
secondHalf = N / halfPower
if (firstHalf == firstHalf and
isCyclic(firstHalf)):
return False

num = N
while (True):

# Following three lines
# generates a
# circular pirmutation
# of a number.
rem = num % 10
div = num // 10
num = pow(10, count – 1) * rem + div

# If all the permutations
# are checked
# and we obtain original
# number exit
# from loop.
if (num == N):
break

if (num % N != 0):
return False

return True

# Driver code

N = 142857
if (isCyclic(N)):
print(“Yes”)
else:
print(“No”)

# This code is contributed
# by Anant Agarwal.

参考资料:

https://codegolf.stackexchange.com/questions/123251/is-it-a-cyclic-number

维基百科


关注微信公众号

码中人 微信公众号

发表评论

电子邮件地址不会被公开。 必填项已用*标注