11

# log[7] all posts are gone and recursion

Note: I mostly blog on my own website

**All The Old Posts Are Gone**

All posts from the last 2 months are gone because while hopping between one blog theme and another I deleted the repo containing the posts. Now, no time to cry so lets go the other topic which is recursion.

recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem. It's a pretty broad topic so just get to the code I'll explain on the way as it's way easier to explain with code.

```
fn f(n: u32) -> u32 { //initialise n as u32 integer
if n < 2 { // if n is lesser than n
1 // raise error
} else {
n * f(n - 1) // else do n into factorial of n - 1
}
}
fn main() {
println!("{} is the factorial of 4 calculated recursively", f(4 as u32)); // print factorial of n where n == 4
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_recursion() {
assert_eq!(f(4), 24)
}
}
```

Lets go over the code function by function now

```
fn f(n: u32) -> u32 { //initialise n as u32 integer
if n < 2 { // if n is lesser than n
1 // raise error
} else {
n * f(n - 1) // else do n into factorial of n - 1
}
}
```

I initialise function f which takes n as an input. Then I say if n is smaller than 2 throw error as the factorial of !1 and !0 are the same ie - 1 and it causes complications in the computer. If it is bigger then run a calculation to find the factorial which is (if n = 4) 4 _ f(4 - 1) == 4 _ f(3). Here the computer runs the same f operation on 3 again as I say n is equals to 3 now.

This happens recursively until n <= 2. Then the computer saves 4 _ f(3) = 24 as f(3) is 6 and f(3) is calculated as 3 _ f(2) = 6,f(2) as 2 * f(1) = 2 and so on.

```
fn main() {
println!("{} is the factorial of 4 calculated recursively", f(4 as u32));
}
```

function main just prints f(4)

Now to the last part, this was the first time I was writing tests in any programming languages and I came up with this

```
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_recursion() {
assert_eq!(f(4), 24)
}
}
```

Setup tests and initialise function test_recursion, test_recursion simply compares the LHS (f(4)) to 24(factorial of 4)

Again I'm very sad all the other articles are gone including the parrotos in gitpod one but what can we do..

I'm probably going to practice more recursion so more posts about recursion soon. Cheers!

11