-
-
Notifications
You must be signed in to change notification settings - Fork 947
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
base: main
Are you sure you want to change the base?
Changes from 1 commit
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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 : | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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. |
||
```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; | ||
} | ||
``` |
There was a problem hiding this comment.
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
?There was a problem hiding this comment.
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 :)