[英]find or generate all octal numbers from 0 to 8^10 that digit sum is equal to x
So given an input of 0o11110000000 base 8 ('0o' is ignored) i have to generate and count how many possible numbers that when the individual numbers are added they are the same.因此,给定 0o11110000000 base 8 的输入('0o' 被忽略),我必须生成并计算在添加各个数字时它们相同的可能数字。 for example
例如
so for an input of 0o0000000001 i should get an answer of 10所以对于 0o0000000001 的输入我应该得到 10 的答案
0000000001
0000000010
0000000100
0000001000
0000010000
0000100000
0001000000
0010000000
0100000000
1000000000
My method is a very very brute force method in which i have to check every possible number from 0 to 7777 7777 77 base8.我的方法是一种非常非常蛮力的方法,我必须检查从 0 到 7777 7777 77 base8 的每个可能的数字。 It uses the decimal represtation of the octal numbers and i use a recursive function to retrieve the octal sum of a number
它使用八进制数的十进制表示,我使用递归 function 来检索一个数的八进制和
How can i improve this to be a lot more faster.我该如何改进它才能更快。 If possible no python modules as i doubt the machine running the program is unable to import a lot of stuff
如果可能的话,没有 python 模块,因为我怀疑运行该程序的机器无法导入很多东西
def sum_of_octal_digits( n ):
if n == 0 :
return 0
else:
return int(n) % 8 + sum_of_octal_digits( int(n / 8) )
octInput = input("Enter hex: ")
int_octInput = int(octInput , 16)
total = sum_of_octal_digits(int_octInput )
allcombinations = list()
for i in range(pow(8,len(e[2:]))):
if sum_of_octal_digits(i) == total :
allcombinations.append(i)
print(len(allcombinations))
You're counting the number of sequences of {0, 1, 2, 3, 4, 5, 6, 7} of length n that sum to t.您正在计算总和为 t 的长度为 n 的 {0, 1, 2, 3, 4, 5, 6, 7} 的序列数。 Call that value
S[n, t]
.将该值
S[n, t]
。
There's a recurrence relation that S[n, t]
satisfies: S[n, t]
满足一个递归关系:
S[0, 0] = 1
S[0, t] = 0 (t != 0)
S[n+1, t] = sum(S[n, t-d] for d=0...min(t, 7))
Once you have the recurrence relation, solving the problem using dynamic programming is straightforward (either by using memoization, or using a bottom-up table approach).一旦你有了递归关系,使用动态规划解决问题就很简单了(通过使用记忆,或使用自下而上的表方法)。
The program should run in O(nt) time and use O(nt) space.该程序应该在 O(nt) 时间内运行并使用 O(nt) 空间。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.