Recursion in Cilk
Here’s the translated code and explanation in Markdown format suitable for Hugo:
Our first example demonstrates recursion, a fundamental concept in programming where a function calls itself. Here’s a classic example of calculating factorials using recursion.
To run the program, compile and execute it using the javac
and java
commands:
In this example, we define a fact
method that calculates the factorial of a given number recursively. The base case is when n
is 0, which returns 1. For any other positive integer, it multiplies n
by the factorial of n-1
.
We also demonstrate how to create a recursive function using an anonymous inner class, which is similar to closures in some other languages. Here, we implement the Fibonacci sequence. The fib
function is defined as an IntUnaryOperator
, which is a functional interface in Java that represents a function that accepts an int-valued argument and produces an int-valued result.
The Fibonacci function checks if the input is less than 2 (base case), and if not, it recursively calls itself for n-1
and n-2
, summing the results.
Both functions are called in the main
method with an argument of 7, and their results are printed.
This example showcases how recursion can be implemented in Java, both with regular methods and with functional interfaces, providing a powerful tool for solving problems that have a recursive nature.