-1

I try coding this sequence:

M(0) = 1,
M(1) = 1, 
M(2) = 2, 
M(2t) = M(t) + M(t + 1) + t (for t > 1), 
M(2t + 1) = M(t - 1) + M(t) + 1 (for t >= 1)
 

So this is my attempt (but still wrong): I don't know how I can differentiate between 2t and 2t +1

function seq(num)
{
    var num1=1;
    var num2=1;var num3=2
    var sum1;var sum2;
    var i=0;                                                             
    if (num>=1){                                                            
      for (i = 0; i < num; i++) {                           
        sum2=num1+num2+1;
        num1=num2;
        num2=sum2; } }                                                          
    if (num>1){
        for (i = 0; i < num; i++)
        {
        sum1=num1+num2+num;
        num1=num2;
        num2=sum1;
       }}
    return num2;
}

document.write("seq(1): "+seq(1)+"<br>");```
ha12
  • 1
  • 1
  • Where is your code differentiating between **even** (`2t`) and **odd** (`2t+1`) positions. – PM 77-1 Jun 16 '22 at 15:52
  • How I can do that? I based my code on (for t > 1) and (for t >= 1). – ha12 Jun 16 '22 at 16:05
  • For example, https://stackoverflow.com/questions/5016313/how-to-determine-if-a-number-is-odd-in-javascript – PM 77-1 Jun 16 '22 at 16:12
  • I strongly suggest that you take paper and pencil and manually write down fist 10 (or so) members of your sequence. You cannot automate something you do not understand. – PM 77-1 Jun 16 '22 at 16:14

1 Answers1

0

From what I understand you have 4 cases:

  • num is equal to 0 or 1 (num < 2)
  • num is equal to 2
  • num is even (num = 2t)
  • num is odd (num = 2t + 1)

In the first case we return 1, in 2nd case we return 2 and in other cases we need to re-call the same function with different parameters (t, t + 1, t - 1)

function seq(num) {
  
  if(num < 2) {return 1; }
  if(num === 2) {return 2; } 
  
  if(num % 2 === 1) {
    const t = (num - 1) / 1;
    return seq(t - 1) + seq(t) + 1;
  }
  
  const t = num / 2;
  return seq(t) + seq(t + 1) + t;
  
}
Cedric Cholley
  • 1,956
  • 2
  • 9
  • 15