检查大数的任何排列是否可以在 Python 中被 8 整除
假设我们有一个巨大的数字,我们必须找出数字的任何排列是否可以被8整除。数字以字符串格式提供给我们。
所以,如果输入是这样的:input_num=4696984,那么输出将是“被八整除”。
为了解决这个问题,我们将用数字的数字检查所有可能的三位数排列,看看它们是否可以出现在数字的任何全数字排列中。如果一个可以被8整除的三位数排列出现在该数的一个全数排列的末尾,我们就会说这个排列可以被8整除。
为了解决这个问题,我们将按照以下步骤操作-
如果input_num的长度<3,则
返回真
返回真
如果input_nummod8与0相同,则
input_num:=input_num的反向
如果input_nummod8与0相同,则
返回错误
temp_arr:=由0初始化的大小为10的新列表。
对于范围0到input_num大小的计数,请执行
temp_arr[input_num[count]-0]:=temp_arr[input_num[count]-0]+1
对于104到999范围内的计数,增加8,执行
进行下一次迭代
进行下一次迭代
进行下一次迭代
温度:=计数
出现次数:=大小为10的新列表,初始化为0。
出现次数[临时模10]:=出现次数[临时模10]+1
温度:=温度/10
出现次数[临时模10]:=出现次数[临时模10]+1
温度:=温度/10
出现次数[临时模10]:=出现次数[临时模10]+1
温度:=计数
如果出现[tempmod10]>temp_arr[tempmod10],则
温度:=温度/10
如果出现[tempmod10]>temp_arr[tempmod10],则
温度:=温度/10
如果出现[tempmod10]>temp_arr[tempmod10],则
返回真
返回错误
让我们看看以下实现以获得更好的理解-
示例
def solve(input_num):
if len(input_num) < 3:
if int(input_num) % 8 == 0:
return True
input_num = input_num[::-1]
if int(input_num) % 8 == 0:
return True
return False
temp_arr = 10 * [0]
for count in range(0, len(input_num)):
temp_arr[int(input_num[count]) - 0] += 1
for count in range(104, 1000, 8):
temp = count
occurences = 10 * [0]
occurences[int(temp % 10)] += 1
temp = temp / 10
occurences[int(temp % 10)] += 1
temp = temp / 10
occurences[int(temp % 10)] += 1
temp = count
if (occurences[int(temp % 10)] >
temp_arr[int(temp % 10)]):
continue
temp = temp / 10
if (occurences[int(temp % 10)] >
temp_arr[int(temp % 10)]):
continue
temp = temp / 10
if (occurences[int(temp % 10)] >
temp_arr[int(temp % 10)]):
continue
return True
return False
if solve("4696984"):
print("Divisible by eight")
else:
print("Not divisible by eight")输入
4696984输出结果
Divisible by eight