Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create mentoring.md for grains exercice in cpp #2339

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here and later: "indice" sounds like French or Italian, right? Since everything else is in English how about index?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I'm french, it happens sometimes that I let a french word in my code. I will do this changes thx :)

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 :

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd argue that it is subjective whether a recursive implementation is "cleaner" than one using a loop.
Personally I prefer the function with the loop, with my imperative mindset I find it a tiny bit easier to understand, and it avoids the overhead of the recursive function call.
If you really want to call it "cleaner" I'd prefer if you make it clear that this is an opinion (like later with the "in my mind".)

```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;
}
```
Loading