Skip to main content
added 200 characters in body
Source Link
AlanK
  • 326
  • 2
  • 6

I know it's a jscript code review, but since you're chasing efficiency it's all about algorithm/formula (rather than language), so here's how to eliminate all the looping (i.e. calculate in O(1)). TryTry it first in Excel...

INT (INT() is traditional TRUNC()/FLOOR() for positive integers
Integerand MOD(a,b) givesis remainder after dividing a by/ b (so we're working only with integers).

N is season number, h the height (at the end of that season)

h = (2^(INT(N/2)+1)-1)*(1+INT(MOD(N,2)))

OutputIn C#

N  for h(int n = 0; n < 10; n++)
  {
    Console.WriteLine($"{n,2}, {(Math.Pow(2, n / 2 + 1) - 1) * (1 + n % 2),3}");
  }

Output

 0,   1
 1,   2
 2,   3
 3,   6
 4,   7
 5,  14
 6,  15
 7,  30
 8,  31
 9,  62

I know it's a code review, but since you're chasing efficiency, here's how to calculate in O(1). Try it first in Excel...

INT() is traditional TRUNC()/FLOOR() for positive integers
Integer MOD(a,b) gives remainder after dividing a by b

N is season number, h the height (at the end of that season)

h = (2^(INT(N/2)+1)-1)*(1+INT(MOD(N,2)))

Output

N   h
0   1
1   2
2   3
3   6
4   7
5  14
6  15
7  30

I know it's a jscript code review, but since you're chasing efficiency it's all about algorithm/formula (rather than language), so here's how to eliminate all the looping (i.e. calculate in O(1)). Try it first in Excel (INT() is traditional TRUNC()/FLOOR() and MOD(a,b) is remainder after a / b (so we're working only with integers).

N is season number, h the height (at the end of that season)

h = (2^(INT(N/2)+1)-1)*(1+INT(MOD(N,2)))

In C#

  for (int n = 0; n < 10; n++)
  {
    Console.WriteLine($"{n,2}, {(Math.Pow(2, n / 2 + 1) - 1) * (1 + n % 2),3}");
  }

Output

 0,   1
 1,   2
 2,   3
 3,   6
 4,   7
 5,  14
 6,  15
 7,  30
 8,  31
 9,  62
Source Link
AlanK
  • 326
  • 2
  • 6

I know it's a code review, but since you're chasing efficiency, here's how to calculate in O(1). Try it first in Excel...

INT() is traditional TRUNC()/FLOOR() for positive integers
Integer MOD(a,b) gives remainder after dividing a by b

N is season number, h the height (at the end of that season)

h = (2^(INT(N/2)+1)-1)*(1+INT(MOD(N,2)))

Output

N   h
0   1
1   2
2   3
3   6
4   7
5  14
6  15
7  30