我正在尝试编写一个代码来执行以下操作:
将整数的数字相乘并继续处理,得到了一个令人惊讶的结果,即产品序列总是到达一个单数数字。
例如:
715 -> 35 -> 15 -> 5 88 -> 64 -> 24 -> 8 27 -> 14 -> 4
达到个位数所需的产品数量称为该整数的持久化数。因此,715和88的持久化数为3,而27的持久化数为2。请编写一个程序来查找持久性大于3的唯一两位数的数字?
我想出了一个粗略的想法,代码如下,但它似乎不起作用:
num2=0
num3=0
num4=0
num=input("what is your number?")
while num in range(10,100):
print 'step1'
num1=num%10*num/10
if num1-10>10:
print 'step2'
num2=num1%10*num1/10
elif num2-num1>10:
print 'step3'
num3=num2%10*num2/10
elif num3-num2>10:
print 'step4'
num4=num3%10*num3/10
elif num4-num3>10:
print 'step5'
print num4
else:
break程序是Python,我根本搞不懂这一点。如果有人能帮我,我会非常感激的!
发布于 2011-11-01 22:37:57
您应该使用时间或for循环来乘以数字,而不是硬编码如何处理第一位、第二位等等。
用伪码..。
productSoFar = 1
digitsLeftToMultipy = #the number
while there are digits left to multiply:
get the next digit and
update produtsSoFar and digitsLeftToMultiply此外,使用
10 <= n < 100而不是
n in range(10, 100)因此,您只做了几次比较,而不是顺序查找,这需要时间成比例的长度范围。
发布于 2011-11-01 22:41:06
功能是朋友。
考虑一个函数getEnds(x),当传递一个整数时,x将提取第一个数字和最后一个数字(作为整数),并在表单(first_digit, last_digit)中以元组形式返回结果。如果x是一个单数数字,元组将包含一个元素并以表单(x)表示,否则它将为两个。(一种简单的方法是将数字转换为字符串,提取第一个/最后一个数字为字符串,然后将所述字符串转换为数字.然而,有许多方法:确保遵守函数契约,正如上面所述,并且--希望--在函数文档中。)
然后,在n是当前数字的情况下,我们找到了以下的持久性:
ends = getEnds(n)
while ends contains two elements
n = first element of ends times second element of ends
ends = getEnds(n)
# while terminates when ends contained only one element
# now it's only a matter of "counting" the persistence对于添加的点,请确保它在一个--一个适当的名称/文档中--函数中,并考虑使用递归函数而不是while-循环。
编码愉快。
发布于 2011-11-01 22:34:17
如果要获取数字的数字,首先将其转换为字符串,并使用数组表示法引用它们。
https://stackoverflow.com/questions/7973690
复制相似问题