Problem of the Day
A new programming or logic puzzle every Mon-Fri

Factorial Finder

Today's objective is to create a function that takes in a number and uses a recursive algorithm to find the factorial of that number. Given the number 9 your program should output 362880.

Permalink: http://problemotd.com/problem/factorial-finder/

Comments:

  • Heroka - 10 years, 3 months ago

    In R:

    factorial <- function(n){
      if(n<=1){ #0! is also 1
        return(1)
      } else{
        return(n*factorial(n-1))
      }
    }
    
    > factorial(9)
    [1] 362880
    

    reply permalink

  • David - 10 years, 3 months ago

    In C by switch.
    I like having 2 also be a base case, because something about bothering to multiply by 1 bugs me.
    Never the less:

    #include <stdio.h>
    
    unsigned int factorial(unsigned int);
    
    unsigned int factorial(unsigned int n) {
        int retval = 1;
        switch(n) {
            case 0:
                break;
            case 1:
                break;
            case 2:
                retval = 2;
                break;
            default:
                retval = n * factorial(n-1);
                break;
        }
        return retval;
    }
    
    int main(void) {
        printf("%i\n", factorial(9));
        return 0;
    }
    

    reply permalink

  • Anonymous - 10 years, 3 months ago

    One of the most satisfying haskell example :D

    fac :: Int -> Int
    fac 1 = 1
    fac n = n * fac (n-1)
    

    reply permalink

  • malboy - 10 years, 3 months ago

    Did this one in C#:

            int numUserInput,
                numAnswer;
    
            Console.WriteLine("Today's objective is to create a function that takes \n" +
                "in a number and uses a recursive algorithm to find the factorial \n" +
                "of that number. Given the number 9 your program should output 362880.");
            Console.WriteLine("Enter a whole number: ");
    
            numUserInput = Convert.ToInt32(Console.ReadLine());
            numAnswer = numUserInput;
    
            while (numAnswer > 1)
            {
                numAnswer -= 1;
                numUserInput = numUserInput * (numAnswer);
            }
    
            Console.WriteLine("Factorial is: " + numUserInput);
            Console.ReadLine();
    

    reply permalink

Content curated by @MaxBurstein