Home > front end >  From 1 to n
From 1 to n

Time:09-22

The small white help, each great god please help bai
To implement a function sum (n) and add 1 to n
Requirement: the execution time O (1), js

CodePudding user response:

 
The function sum (n) {
Var s=0;
For (var I=1; i <=n; I++) {
S +=I;
}
return s;
}
Alert (sum (100));

CodePudding user response:

Let the sum=0;
Let n=10000;
For (the let I=0; i<=n; I++) {
The sum +=I;
}
The console. The log (sum)

CodePudding user response:

Said the execution time O (1) the first floor and second floor funny? Come up & lt;=n upstairs that is 10000 times I'm drunk
 the function sum (n) {return (n) * (1 + parseInt (n/2)) - (n& 1==1? Zero: n/2); 

Looking for regular n=9 1 2 3 4 5 6 7 8 9 can add as 9 1 2 3 4 5 6 7 45 odd number five and nine plus don't add
N=10 1 2 3 4 5 6 7 8 9 10 is 1 2 3 4 5 6 7 8 9 10 5 10 plus 10/2 is not found in the middle of the 50 + 10/2 even Numbers

CodePudding user response:

 the function sum (n) {
Return n * (1 + n)/2;
}
  • Related