-
-
Notifications
You must be signed in to change notification settings - Fork 946
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create mentoring.md for grains exercice in cpp
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
1 parent
57b0d21
commit dfbe8e0
Showing
1 changed file
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
``` |