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

Optimize printFib using lists to build strings #14

Merged
merged 3 commits into from
Oct 6, 2021
Merged
Changes from all commits
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
10 changes: 6 additions & 4 deletions src/math/math.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@ let getGcd = (arg1, arg2) => {
* @param {Number} arg_n n'th natural number
* @returns return a `n'th fibonacci` number.
*/


let getFib = (arg_n) => {
if(arg_n == 0 || arg_n == 1) return arg_n;
let [a, b] = [0, 1];
Expand All @@ -35,18 +37,18 @@ let getFib = (arg_n) => {
* @param {Number} n n'th natural number
* @returns return a `series` of n'th fibonacci numbers.
*/
let printFib = (n) => {
let printFib = (n) => {
let num1 = 1;
let num2 = 0;
let num3 = 0;
let st = "";
let st = [];
for(let i=0;i<n;i++){
num3 = num1 + num2;
st = st + num3 + ' ';
st.push(num3);
num1 = num2;
num2 = num3;
}
return("Fibonacci Series : "+st);
return("Fibonacci Series : "+st.join(' '));

Choose a reason for hiding this comment

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

I think there is no optimization here. and through the string.join() you have added another loop if you are not satisfied with my opinion please let me know.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

When you add to a string like s=s+'a' , you have to create a whole new new string, which is not a problem with short strings but can get a little inefficient with long strings, so with big strings adding to a list is constant time rather than making a whole new string.
The optimization is not that big, and in modern systems it is not that big of a difference, so if you want you can ignore this pull or include it, up to you.

Choose a reason for hiding this comment

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

Yeah, you're right :)

}

// sumAllDigit return the addition of all the digits in a given number.
Expand Down