Skip to content

Commit

Permalink
Create mentoring.md for grains exercice in cpp
Browse files Browse the repository at this point in the history
Creating the guide for the solution of the grains exercise in cpp. Offering an imperative and a recursive solution for the first function and explaining how to do correctly the second function.
  • Loading branch information
CornierQuentin authored Apr 7, 2024
1 parent 57b0d21 commit dfbe8e0
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions tracks/cpp/exercises/grains/mentoring.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# Mentoring

## First function

The first way to implement this function is to use a for loop :
```cpp
unsigned long long square(int indice) {
unsigned long long result = 1;
for (int i = 0; i < indice; i++) result *= 2;
return result;
}
```
A cleaner way to do this is to use a recursive function :
```cpp
unsigned long long square(int indice) {
if (indice == 1) return 1;
else return square(indice - 1) * 2;
}
```
This way, the code is shorter and in my mind, easier to read.

## Second function
At first sight, we want to use the first function to do it easily :
```cpp
unsigned long long total() {
unsigned long long sum = 0;
for (int i = 1; i <= 64; i++) sum += square(i);
return sum;
}
```
However with this solution, each time you call the function square with the indice i, you do i products.
In the following solution, you only do 64 products and by adding to the sum each time you multiply by 2 :
```cpp
unsigned long long total() {
unsigned long long total = 0;
unsigned long long square = 1;

for (int k = 0; k < 64; k++) {
total += square;
square *= 2;
}

return total;
}
```

0 comments on commit dfbe8e0

Please sign in to comment.