How to resolve the algorithm Mutual recursion step by step in the Mathematica/Wolfram Language programming language
How to resolve the algorithm Mutual recursion step by step in the Mathematica/Wolfram Language programming language
Table of Contents
Problem Statement
Two functions are said to be mutually recursive if the first calls the second, and in turn the second calls the first. Write two mutually recursive functions that compute members of the Hofstadter Female and Male sequences defined as:
(If a language does not allow for a solution using mutually recursive functions then state this rather than give a solution by other means).
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Mutual recursion step by step in the Mathematica/Wolfram Language programming language
This code defines a pair of recursive functions called f
and m
that are used to generate two sequences of numbers. The sequences are defined as follows:
f[n] = n - m[f[n-1]]
m[n] = n - f[m[n-1]]
The code first defines base cases for the functions f
and m
when n = 0
. Then, it defines the recursive definitions of the functions.
f[0] := 1
m[0] := 0
f[n_] := n - m[f[n - 1]]
m[n_] := n - f[m[n - 1]]
The code then uses the /@
operator to apply the functions f
and m
to the range of integers from 0 to 29. The results are printed to the console, showing the values of f[n]
and m[n]
for each value of n
in the range.
The output is as follows:
{0, 1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12, 12, 13, 14, 14, 15, 16, 16, 17, 17, 18, 19}
{1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 8, 8, 9, 9, 10, 11, 11, 12, 13, 13, 14, 14, 15, 16, 16, 17, 17, 18, 19}
The sequence generated by f[n]
is the Fibonacci sequence, which is a sequence of numbers where each number is the sum of the two preceding numbers. The sequence generated by m[n]
is the Lucas sequence, which is a similar sequence to the Fibonacci sequence, but with different starting values.
Source code in the wolfram programming language
f[0]:=1
m[0]:=0
f[n_]:=n-m[f[n-1]]
m[n_]:=n-f[m[n-1]]
f[0]:=1
m[0]:=0
f[n_]:=f[n]=n-m[f[n-1]]
m[n_]:=m[n]=n-f[m[n-1]]
m /@ Range[30]
f /@ Range[30]
{0,1,2,2,3,4,4,5,6,6,7,7,8,9,9,10,11,11,12,12,13,14,14,15,16,16,17,17,18,19}
{1,2,2,3,3,4,5,5,6,6,7,8,8,9,9,10,11,11,12,13,13,14,14,15,16,16,17,17,18,19}
You may also check:How to resolve the algorithm Hilbert curve step by step in the Seed7 programming language
You may also check:How to resolve the algorithm Faulhaber's formula step by step in the Kotlin programming language
You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the Mathematica/Wolfram Language programming language
You may also check:How to resolve the algorithm Problem of Apollonius step by step in the Arturo programming language
You may also check:How to resolve the algorithm Loops/While step by step in the Quackery programming language