how to code a factorial

戏子无情 提交于 2019-12-11 03:19:39

问题


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.

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.

    // 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

Type a number: 10 Factorial is 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.


回答1:


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);
 }
}



回答2:


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

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)
                 }
         }
    



回答3:


The problem is here

  sum = factorial + userIn + extra;

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

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
  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.




回答4:


// 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



回答5:


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);
}


来源:https://stackoverflow.com/questions/23692893/how-to-code-a-factorial

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!