Switch the screen on/off Go back to last page Go forward one page Find out more details about the advertisement
John Moores University. Main CWIS Site
  

   

Update Operators

The binary update operators :+, :-, :*, and :/ respectively increment, decrement, multiply, and divide the variable on their left by the amount on their right.  For example, n :-1 is equivalent to, but more efficient than  n := n-1.  Similarly, n :* 2 is equivalent to n := 2*n.

 

Earlier, we mentioned that the FACT(n) function was not written as efficiently as it could be.  This is because we did not use update operators.  The function definition of FACT(n) below is more efficient.  You can copy and paste the next line into the Entry Line of Derive if you wish!

FACT(n, total) := PROG(total := n, LOOP(IF(n = 2, RETURN total), total :* n - 1, n :- 1))

Which displays as

FACT(n, total) :=
    Prog
   
   total := n
      Loop   
        If n = 2
           RETURN total  
      
total :* n - 1
       n :- 1  

As an exercise you may like to compare the computation times of FACT(1000) using the definitions with and without the use of update operators.

The FACT(n) program is still not complete, as it will only work if n is a positive integer.  A user may well try to use a value other than an integer for n.  Clearly this would cause an infinite loop.  Also, 0! And 1! are defined as 1, so FACT(n) is not watertight at the moment.  The 0! Issue is easily addressed by adding the lines IF(n=0, RETURN 1), IF(n=1, RETURN 1) at the beginning.  The issue of n being a positive integer can be addressed easily when we look at predicate functions for recognising the data type of expressions.  However, even without these functions we can still tighten up the definition of FACT(n).  But before we do this we will introduce the Boolean operators.

Move on to Boolean Operators

Return to Programming Basics