【问题标题】:I need to calculate the result for 1!/1 + 2!/2 + 3!/3 + n!/n in a Java program我需要在 Java 程序中计算 1!/1 + 2!/2 + 3!/3 + n!/n 的结果
【发布时间】:2016-08-07 09:20:39
【问题描述】:

我被困在这里:

System.out.println("输入要添加到这些阶乘数字中的数字:"); System.out.println("1!/1 + 2!/2 + 3!/3 + "); //阶乘,即。 5!/5 = 4 * 3 * 2 * 1 n = scan.nextInt();

     while (!exit)
    {

        if (n <= 2) 
        {
            sum = 1;
            exit = true;
        }
        sum = sum + i - 1;

        i = i - 1;
        if (i == 2)
        {
            exit = true;
        }
    }

     //m2 = 1 * 1 + (2 * 2) + (2 * 1) + (3 * 3) + (3 * 2) + (3 * 1) + (n * n -1);  
     //System.out.println(m2);

【问题讨论】:

  • 你卡在哪里了?
  • 您的问题是什么,究竟?什么程序会出错?
  • 我想要一些输入和所需的输出示例。
  • 所以你不知道如何计算阶乘?
  • 为什么是n!/n 而不是(n-1)!

标签: java math


【解决方案1】:

似乎n 没有改变。因此,您可以将其移出while 循环。你要求阶乘,但我在这里找不到*。也许你可以用for循环试试这个:

// say you got n = sth here
int sum = 0;
int factorial = 1;
for(int i = 1; i <= n; i++) {
    // so factorial = i!
    factorial = factorial * i; 
    // add i!/i to sum, all the way to n!/n
    sum = sum + factorial / i; 
}
// sum is the result.
return n;

【讨论】:

  • 需要发生的是。我需要计算下一个 int 输入“n”的阶乘并将其添加到等式的其余部分(1!/1 + 2!/2 + 3!/3 + n!/n = ?)。我不确定在哪里以及如何向程序解释这是如何计算 n!/n?
【解决方案2】:

我认为您的主要问题是实现阶乘函数。有两种基本方法可以做到这一点:

迭代,使用循环:

public static long factorialWhileLoop(int n) {
    long result = 1;
    while (n > 1) {
        result *= n--;
    }
    return result;
}

或者递归,我更喜欢它,因为它没有赋值:

public static long factorialRecurse(int n) {
    return n <= 1 ? 1 : n * factorialRecurse(n - 1);
}

正如其他人已经提到的,要计算n!/n,只需使用(n-1)!

如果您想要更高的性能,请使用查找表:

static final int [] FACTORIALS =
    {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880,
     3628800, 39916800, 479001600, 6227020800L, 87178291200L,
     1307674368000L, 20922789888000, 355687428096000,
     6402373705728000, 121645100408832000, 2432902008176640000,
 };

int factorial(int n) {
    if (n < 0 || n >= FACTORIALS.length ) throw new Exception();
    return FACTORIALS[n];
}

64位整数可以表示的阶乘并不多。

但是,如果您需要更大的阶乘,还有其他专门的方法。

【讨论】:

  • 这里提供的迭代器和递归实现都不是一个好主意。对于较大的 n,两者都尽可能低效。更好的解决方案是使用 gamma 函数和记忆。为什么要不断重新计算昂贵的阶乘?
  • @duffymo:没错,但说真的,OP 显然是初学者,在实现 any 阶乘函数时遇到了麻烦。你真的认为在这里建议 gamma 函数或 memoization 有意义吗?但是好的,我将在我的答案中添加查找表方法。
  • 我同意有很多经验丰富的程序员不知道伽玛函数是什么;它远远超出了甚至没有想过编写阶乘函数的人。这是一条针对所有认为天真的阶乘实现是唯一出路的人的评论。
猜你喜欢
  • 2012-07-30
  • 1970-01-01
  • 1970-01-01
  • 2010-12-02
  • 2022-06-17
  • 2020-01-10
  • 2011-01-29
  • 1970-01-01
相关资源
最近更新 更多