Java 如何编码阶乘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23692893/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 00:44:35  来源:igfitidea点击:

how to code a factorial

javafactorial

提问by Casey French

my question is not so much about code as it is the logic behind writing a factorial program. I am currently taking a MOOC at the University of Helsinki and I have become stuck on this exercise. As the course moves on to new exercises the instructions have become more and more vague. I realize this probably isn't the place to ask this question and if you must tag it or remove it, I do understand. I am trying to learn this on my own as I do not have the time or money to actually attend a university. This course has no time constraint and I wont be receiving a certificate of achievement for it, I simply want the knowledge.

我的问题不是关于代码,而是编写阶乘程序背后的逻辑。我目前正在赫尔辛基大学参加 MOOC 课程,但我一直坚持这项练习。随着课程进入新的练习,说明变得越来越模糊。我意识到这可能不是问这个问题的地方,如果你必须标记或删除它,我明白。我正在尝试自己学习这一点,因为我没有时间或金钱实际上大学。这门课程没有时间限制,我不会因此获得成绩证书,我只是想要知识。

these are the instructions given for the exercise

这些是练习的说明

Create a program that calculates the factorial of the number n. The factorial n! is calculated using the formula 1*2*3*...*n. For example 4! = 1*2*3*4 = 24. Additionally, it is defined that 0! = 1.

创建一个程序来计算数字 n 的阶乘。阶乘 n!使用公式 1*2*3*...*n 计算。例如4!= 1*2*3*4 = 24。另外,定义为 0! = 1。

    // i don't understand the example that 4!= 1*2*3*4 = 24 
    // or how 0! = 1 pertains to multiplying numbers in succession to find the
    // factorial of the user input number.
    // i understand that 0! = 1 simply delclares that 0 is not equal to 1 
    // and 4 is not equal to 24, however if the 4! = portion of this statement
    // is in reference to the user input number 4 that statement would not be
    // true as 1*2*3*4 does equal 24 and 4 would be the number of executions
    // of the block execution of the loop required to write the factorial 
    // program.

   // EDIT: okay so according to this http://en.wikipedia.org/wiki/Factorial
   // i am wrong about what is being done here as they are not declaring 
   // that 4 not equals 24 but yet that 4! is a way of correlating the non
   // negative numbers up to 4, but given that math is not my strong suit 
   // it is even more confusing to me as to what i should be doing.

Example outputs:

示例输出:

Type a number: 3 Factorial is 6

输入一个数字:3 阶乘是 6

Type a number: 10 Factorial is 3628800

输入数字:10 阶乘是 3628800

my current code attempt is as follows

我目前的代码尝试如下

     public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);



    System.out.println("Type a number:");
    int userIn = Integer.parseInt(reader.nextLine());
    int factorial = 1;
    int extra = 1;
    int sum = 0;

    while (factorial <= userIn) {
        factorial++;
        sum = factorial + userIn + extra;
        }
    System.out.println("The factorial is:"+sum);
    }
}

I do not understand what it is that i am missing, i know from research that in the real world you would not code this as there are libraries you can download to perform the factorial function that are much more efficient than what i could code, but i don't want to simply skip this exercise with the knowledge that someone else has already coded and created a library to make our lives easier, i want to learn everything that this course has to offer. if i have made a simple error i don't mind an offered code correction, however i want to understand what makes the factorial operation tick so to speak, not just be given the answer so i can move on.

我不明白我错过了什么,我从研究中知道在现实世界中你不会编码这个,因为你可以下载一些库来执行比我可以编码的更有效的阶乘函数,但是我不想简单地跳过这个练习,因为其他人已经编码并创建了一个库来让我们的生活更轻松,我想学习这门课程所提供的一切。如果我犯了一个简单的错误,我不介意提供的代码更正,但是我想了解是什么使阶乘运算可以这么说,而不仅仅是给出答案以便我继续前进。

采纳答案by Afzal Ahmad

Try this one if you don't want to use an external function

如果你不想使用外部函数,试试这个

public static void main(String[] args) {
   Scanner reader = new Scanner(System.in);
   System.out.println("Type a number:");
   int userIn = Integer.parseInt(reader.nextLine());
   int factorial = 1;
   int i= userin;
   while (userin >= 1) {
    factorial *= userIn;
    userin--;
   }
  System.out.println("The factorial is:"+factorial);
 }
}

回答by Mustafa sabir

The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. Eg:- 4!=1*2*3*4 . 0!=1 states that factorial of 0 is 1 and not that 0 is not equal to 1. The value of 0! is 1, according to the convention for an empty product. An empty product, or nullary product, is the result of multiplying no factors. It is by convention equal to the multiplicative identity 1 , just as the empty sum—the result of adding no numbers—is by convention zero (Like the sum of first 0 natural numbers would we 0), the additive identity. For more on empty products read here http://en.wikipedia.org/wiki/Empty_product

非负整数 n 的阶乘,用 n! 表示,是所有小于或等于 n 的正整数的乘积。例如:- 4!=1*2*3*4 。0!=1 表示 0 的阶乘是 1 而不是 0 不等于 1。0 的值!根据空产品的约定,为 1。空乘积或零乘积是不乘任何因子的结果。按照惯例,它等于乘法恒等式 1 ,就像空和(不加任何数字的结果)按照惯例是零(就像前 0 个自然数的和会是 0),加法恒等式。有关空产品的更多信息,请阅读此处http://en.wikipedia.org/wiki/Empty_product

For the programming part, there are basically two approaches to a factorial program:-

对于编程部分,阶乘程序基本上有两种方法:-

  1. Using a for loop (No recursion)

     int factorial ( int input )
     {
        int x, fact = 1;
         for ( x = input; x > 1; x--) // iterating from n -> n-1 -> n-2 ... 1
          {
             fact *= x;              // multiplying each number into the fact variable to get the factorial
           }
          return fact;
      }
    
  2. Recursive approach -The function calls itself ( Note- avoid using this approach in actual programming as it may be highly resource consuming and bug prone, As pointed out by "Edwin Buck" in the comments)

     public int Factorial(int n)
       {
        if (n == 0) 
             {
            return 1; //Base condition - If factorial reaches 0 return 1 and end recursion
              }
        else
                {
            return n * Factorial(n-1); // For factorial of n, function returns n * Factorial(n-1) i.e recursively calling  the factorial function with one less value in the parameter untill 0 is reached (upon which base condtiion will be evaluated)
                 }
         }
    
  1. 使用 for 循环(无递归)

     int factorial ( int input )
     {
        int x, fact = 1;
         for ( x = input; x > 1; x--) // iterating from n -> n-1 -> n-2 ... 1
          {
             fact *= x;              // multiplying each number into the fact variable to get the factorial
           }
          return fact;
      }
    
  2. 递归方法 - 函数调用自身(注意 - 避免在实际编程中使用这种方法,因为它可能会占用大量资源并且容易出错,正如评论中的“Edwin Buck”所指出的那样)

     public int Factorial(int n)
       {
        if (n == 0) 
             {
            return 1; //Base condition - If factorial reaches 0 return 1 and end recursion
              }
        else
                {
            return n * Factorial(n-1); // For factorial of n, function returns n * Factorial(n-1) i.e recursively calling  the factorial function with one less value in the parameter untill 0 is reached (upon which base condtiion will be evaluated)
                 }
         }
    

回答by Edwin Buck

The problem is here

问题就在这里

  sum = factorial + userIn + extra;

where you "calculate" your factorial from the latest factorial++value in the loop.

factorial++循环中的最新值“计算”阶乘的地方。

You can't calculate factorials from sums in this manner. Factorials are products of all the integers between 1 and the "factorial" number, so

您不能以这种方式从总和中计算阶乘。阶乘是 1 和“阶乘”数之间所有整数的乘积,所以

  1! = 1
  2! = 1 * 2
  3! = 1 * 2 * 3
  4! = 1 * 2 * 3 * 4

If you start off calculating your factorial wrong, then the other parts of the problem don't matter much, they will be wrong by extension.

如果你开始计算你的阶乘错误,那么问题的其他部分就不重要了,它们会因扩展而错误。

回答by pankaj katiyar

// Factorial example (ie 5 * 4 * 3 * 2 * 1)
function factorial($n) {

    if ($n == 1) return 1;
    return $n * factorial($n-1);

}

echo factorial(5); // Outputs 120
// Nested Array Summing Example
$example = array(1, 2, array(10,20,30), 4);

function sum_array($array) {

    $total = 0;
    foreach ($array as $element) {
        if(is_array($element)) {
            $total += sum_array($element);
        } else {
            $total += $element;
        }
    }
    return $total;

}
echo sum_array($example); // Outputs 67

回答by Mikael Bj?rkqvist

Your question is similar to mine, and it was actually a school assignment. Though question is answered, i will contribute my solution.

你的问题和我的差不多,其实是学校的作业。虽然问题得到了回答,但我会贡献我的解决方案。

public static void main(String[] args) {
    Scanner reader = new Scanner(System.in);

    int i = 1;
    int factorial = 1;

    System.out.println("Give number: ");
    int number = Integer.parseInt(reader.nextLine());

    while (i <= number) {
        factorial = factorial * i;
        i++;   
    }
    System.out.println("Answer is " + factorial);
}