- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我正在研究一种算法,其中我们有两个输入、一个总量和一个功率值。我们必须找到总和为总数的幂参数的唯一数字组合的总数。
例如:给定 amount = 10 和 power = 2,只有一个唯一的解决方案:(1^2) + (3^2) = 10
(问题出自这里:https://www.hackerrank.com/challenges/the-power-sum)
到目前为止,这是我的算法:
def count_unique_combos(total, candidate, power)
return -1 if total < 0 || candidate > total # this means impossible to continue
return 1 if total == 0 # arrived at our goal
num_ways = 0
# all the ways to get the total amount, if we use candidate ** power
with_candidate = count_unique_combos(total - candidate ** power, candidate + 1, power)
num_ways += with_candidate if with_candidate != -1
# all the ways to get the total amount without using the candidate.
without_candidate = count_unique_combos(total, candidate + 1, power)
num_ways += without_candidate if without_candidate != -1
num_ways
end
这就是我感到困惑的地方。我已经阅读了很多关于递归算法的信仰飞跃的文章,其中您假设您具有适用于 N-1 输入的函数,并且您只需要使其适用于输入大小 N 并放入正确的基本情况。
基本情况对我来说似乎是合理的,递归关系也是如此(获取所有具有此数字的唯一组合,获取所有没有此数字的组合)。
但是,我的输出不正确。对于 amount = 10 和 power = 2,我的结果值为零。有谁知道我在哪里不符合逻辑?
最佳答案
尝试交换基本案例
return 1 if total == 0 # arrived at our goal
return -1 if total < 0 || candidate > total # this means impossible to continue
当 total == 0
时,您传入的任何候选人(因为您只会增加候选人)将成为 candidate > total
并且您将以-1,然后再检查您是否达到了积极的基本情况。
当你交换它们时(使用 tadman 的测试用例,以便于比较)
count_unique_combos(10, 1, 2)
# => 1
count_unique_combos(100, 1, 2)
# => 3
count_unique_combos(100, 1, 3)
# => 1
关于ruby - 幂和递归算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45090077/
我在编写数学函数时遇到了麻烦。它应该接受 3 个变量并像这样计算方程。 答案 = x(1 + y/100)^ z 我把它写成: public compute_cert (int years, doub
我正在开发一个计算器,以便更好地学习 Java。我编写了自己的代码来使用 BigDecimal 参数计算幂。截至目前,代码无法处理分数幂,例如 2^2.2。为了解决这个问题,我想在我的代码中实现指数恒
我正在寻找一种算法(或者更好的是,代码!)来生成幂,特别是奇数指数大于 1 的数字:三次幂、五次幂、七次幂等等。然后我想要的输出是 8, 27, 32, 125, 128, 216, 243, 343
在 Codewars 上找到这个。该函数接受两个参数 A 和 B,并返回 A^B 的最后一位。下面的代码通过了前两个测试用例,但不会通过下一个测试用例。 def last_digit(n1, n2):
像 2^(2%1) 这样的表达式在 GHCi 中不会进行类型检查,并且错误消息是神秘的。为什么这不起作用,我需要改变什么? 我无法转换为其他类型,我希望将其用于 27^(1%3) 等表达式。 最佳答案
我的二次幂没有达到应有的水平,所以我想也许我可以 #define 做点什么。 不幸的是,我在预处理器指令方面经验不足,我不知道如何做 for 循环之类的事情。我看了看: http://www.cplu
如何在 Math.net 中获得三角函数的幂? Expr x = Expr.Variable("x"); Expr g = (2 * x).Sinh().Pow(2); g.ToString()给出输
我正在尝试拟合这个渐近接近零(但从未达到它)的数据。 我相信最好的曲线是逆逻辑函数,但欢迎建议。关键是预期的衰减“S 曲线”形状。 这是我到目前为止的代码,以及下面的绘图图像,这是一个非常丑陋的适合。
这个问题在这里已经有了答案: The most efficient way to implement an integer based power function pow(int, int) (2
我试图获得指数非常大的 double 值的幂(Java BigInteger 可以包含它(指数),例如:10^30 ) 也就是说,我想找到类似 1.75^(10^30) 或 1.23^(3423453
我有一个数学表达式,例如: ((2-x+3)^2+(x-5+7)^10)^0.5 我需要更换 ^符号到pow C语言的功能。我认为正则表达式是我需要的,但我不知道像专业人士那样的正则表达式。所以我最终
这是我的 previous question on bit flags 的后续内容,我澄清了一些重大误解。 我需要创建这些函数来查找包含零个或多个标志的 int 中的单个位标志: BitBinaryU
我已经在 java 中为 BigInteger 尝试过 modPow() 函数。 但它需要太长时间。 我知道模乘法,甚至也知道求幂。 但由于条件限制,我无法解决这个问题。 a、b 的值可以包含 100
我是一名优秀的程序员,十分优秀!