patternjavascriptModerate
Summing the first 1 to n powers of 2
Viewed 0 times
summingthepowersfirst
Problem
At a JavaScript test for a job, I was asked the question below. I believe there has to be a better way to accomplish the same result, but I couldn't find any. If some JavaScript geek would take a look and suggest a better approach I would really appreciate it:
Given a positive integer greater or equal to 1, write a function f(n) to calculate as efficiently as possible the sum of the first 1 to n powers of 2. Do no use any buit-in function to calculate the power of a number.
Example: if n = 3:
$$ f(3)=2^1+2^2+2^3=2+4+8=14 $$
jsFiddle
Given a positive integer greater or equal to 1, write a function f(n) to calculate as efficiently as possible the sum of the first 1 to n powers of 2. Do no use any buit-in function to calculate the power of a number.
Example: if n = 3:
$$ f(3)=2^1+2^2+2^3=2+4+8=14 $$
jsFiddle
function solution (n) {
var t='';
var q='';
for (var i=1;i<=n;i++) {
q='';
for (var j=1;j<=i;j++) {
q=q+'2*';
}
q=q+1;
t=t+'('+q+')+';
}
t=t.substr(0,t.length-1);
return eval(t);
}Solution
EVAL, WHY!?
I really can't understand why you're using String concatenation and
The most efficient way is to calculate \$2^{n+1}-2\$.
Additionally, your variable names are all one character long, and your code lacks spacing.
How can you tell what is
Another solution is to use bit shifting: (only works if \$n <= 29\$)
I really can't understand why you're using String concatenation and
eval to calculate the result.The most efficient way is to calculate \$2^{n+1}-2\$.
Additionally, your variable names are all one character long, and your code lacks spacing.
How can you tell what is
t and what is q? Your variable names make no sense.function solution (n) {
var result = 2;
for (var i = 1; i <= n; i++) {
result *= 2;
}
return result - 2;
}Another solution is to use bit shifting: (only works if \$n <= 29\$)
function solution(n) {
return (2 << n) - 2;
}Code Snippets
function solution (n) {
var result = 2;
for (var i = 1; i <= n; i++) {
result *= 2;
}
return result - 2;
}function solution(n) {
return (2 << n) - 2;
}Context
StackExchange Code Review Q#84447, answer score: 14
Revisions (0)
No revisions yet.