写一个降幂方法

public static long fallingPower(int n, int k)

然而,在许多组合公式中有用的相关运算中,在语法上通过下划线表示指数,乘积中的每一项总是比前一项少一个。例如,下降功率 83 将计算为 8 * 7 * 6 = 336。类似地,下降功率 105 将等于 10 * 9 * 8 * 7 * 6 = 30240。如果基数 n 为负,则没有任何重要变化。例如,下降功率 (-4)5 的计算方式与 -4 * -5 * -6 * -7 * -8 = -6720 完全相同。


此方法应计算并返回下降幂 nk,其中 n 可以是任何整数,k 可以是任何非负整数。(类似于普通的幂,n0 = 1 表示任何 n。)自动测试器的设计使您的方法无需担心潜在的整数溢出,只要您使用 long 类型的 64 位整数执行计算。


public static long fallingPower(int n, int k)

    long result = n;


    for (int i = n; i < k; i--) {

      result = result * n;

    }


    return result;

  }

我的方法对吗?


慕标琳琳
浏览 94回答 4
4回答

跃然一笑

它应该是:public static long fallingPower(int n, int k){long result = n;for (int i = 0; i < k; i++) {&nbsp;n=n-1;&nbsp;result = result * n;}return result;}

森林海

public static long fallingPower(int n, uint k){&nbsp; &nbsp; long result = 1;&nbsp; &nbsp; for(; k > 0; k--, n--){&nbsp; &nbsp; &nbsp; &nbsp; result *= n;&nbsp; &nbsp; }&nbsp; &nbsp; return result;}

海绵宝宝撒

你应该乘以k时间,从每个因子开始n并递减一个。您的代码目前没有任何意义。我会这样做:public static long fallingPower(int n, int k)&nbsp; &nbsp; long result = n;&nbsp; &nbsp; for (int i = 1; i < k; i++) {&nbsp; &nbsp; &nbsp; result = result * (n-i);&nbsp; &nbsp; }&nbsp; &nbsp; return result;}k必须是非负的,所以你也需要在方法中处理它,例如有一个例外:public static long fallingPower(int n, int k)&nbsp; &nbsp; if(k < 0) {&nbsp; &nbsp; &nbsp; &nbsp; throw new IllegalArgumentException("Negative exponent");&nbsp; &nbsp; }&nbsp; &nbsp; long result = n;&nbsp; &nbsp; for (int i = 1; i < k; i++) {&nbsp; &nbsp; &nbsp; result = result * (n-i);&nbsp; &nbsp; }&nbsp; &nbsp; return result;}

慕姐8265434

如果我没记错的话,这更多的是编程逻辑,而不是你的方法。我没有错误处理。我开始像你一样倒退,假设零的最小整数排列等于 1,至少我们需要返回 1。你可以从 n 之前的 k 个数字开始,然后乘以直到达到 n。public static long fallingPower(int n, int k)&nbsp;{&nbsp; &nbsp; long result = 1;&nbsp; &nbsp; for (int i = 1 ; i <= k ; i++) {&nbsp; &nbsp; &nbsp; result = result * n;&nbsp; &nbsp; &nbsp; n = n-1;&nbsp; &nbsp; }&nbsp; &nbsp; return result;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java