- XLogo library of procedures
These procedures use recursive techniques. They can be very inefficient and are not always the best method to use.
Download library of recursive procedures.
Add
Add two numbers, using recursion. I must be greater
than 0.
To Add :I :J
# return sum of two input numbers
If :I = 0 [Output :J] [Output Add :I-1 :J+1]
End
To Test
# test procedure
Make "A 36 Make "B 12
Print (Sentence [The sum of] :A [and] :B [is] Add :A :B)
End
Factorial
Return the factorial of a number. For example, factorial 6 = 6x5x4x3x2x1
= 720. It is written 6! sometimes spoken as '6 bang'.
To Factorial :N
# return factorial of N
If :N = 1 [Output 1] [Output :N * Factorial :N-1]
End
To Test
# test procedure
Make "A 12
Make "Factorial Factorial :A
Print (Sentence [The factorial of] :A [is] :Factorial)
End
Fibonacci
Return the Nth Fibonacci number. N must be greater than 0.
To Fib :N
# return Nth Fibonacci number
If :N < 2 [Output :N] [Output (Fib :N-1) + Fib :N-2]
End
To Test
# test procedure
Make "N 12
Print (Sentence [The] :N [th Fibonacci number is] Fib :N)
End
Highest Common Factor (HCF)
Also called Greatest Common Denominator (GCD) or Greatest Common Multiple
(GCM).
This procedure uses Euclid's algorithm (dating from ancient Greek times
c.300BC), to generate the highest common factor (HCF) of two numbers.
For example, the HCF of 18 and 24 is 6. Because 6 is the largest whole
number that will divide into both 18 and 24 exactly.
HCF 18 24 and HCF 24
18 will produce the same result.
To HCF :I :J
# return highest common factor of two integers
LocalMake "Rem Modulo :I :J
If :Rem =0 [Output :J]
[Output HCF :J :Rem]
End
To Test
# test procedure
Make "A 3654 Make "B 1365
Print (Sentence [Highest common factor of] :A [and] :B [is] HCF :A :B)
End
Lowest Common Multiple (LCM)
This procedure returns the lowest common multiple of two values by using
the highest common factor (HCF) procedure.
To LCM :I :J
# return lowest common multiple of two integers
Output :I*:J / HCF :I :J
End
To HCF :I :J
# return highest common factor of two integers
LocalMake "Rem Modulo :I :J
If :Rem =0 [Output :J]
[Output HCF :J :Rem]
End
To Test
# test procedure
Make "A 9 Make "B 42
Print (Sentence [Lowest common multiple of] :A [and] :B [is] LCM :A :B)
End
Sum 1 to N
Return the sum of numbers 1 to N. eg Sum1toN 5 = 1+2+3+4+5 = 15.
To Sum1toN :N
# return sum of integers 1 to N
If :N<1 [Output 0] [Output :N+ Sum1toN :N-1]
End
To Test
# test procedure
Make "N 5
Print (Sentence [The sum of 1 to] :N [is ] Sum1toN :N)
End