]> Examples

Examples

  1. Compute the factorial of n

    The factorial of n is computed by multiplying 1 * 2 * 3 * ... * n.

    We can only compute this type of result by hand, if we know n. But, when we use a programming tool like Matlab or Maple or Fortran or C/C++, we can write a program that will compute the correct factorial as soon as we give a correct input.

    Try to create a list of steps that could be followed generically to find the factorial of n and save it with the name "answer". Assume that a named variable "n" has already been given (assigned) a numeric value.

    The basic idea is to create a couple of new variables. "answer" will start at 1 and then hold the new value of the factorial after each multiplication step. A variable named "k" will keep track or count of where we are so far. Then, "loop" through the numbers from 1 to n and multiply each number times the current value of "answer".

    Matlab Solution 1

    > answer = factorial(3)

    Matlab Solution 2

    What if there were no pre-defined factorial command?

      if n > 1 && rem(n,1)==0 % check for a valid n value
        answer = 1;
        for k = 2:n           % loop through all values
           answer = answer * k;  % reassign our answer value
        end
      end
      

    Maple Solution 1

    > answer = factorial(3)

    Maple Solution 2

    We can program in Maple, but it looks somewhat different.

      if evalb(n>1) and mod(n,1)=0 then
         answer := 1;
         for k from 2 by 1 to n do
            answer := answer * k
         end do:
      end if