skip to Main Content

I’m working on this Math recursive question.
What is needed to do is when I put in 0 to the console, it should display the answer then take that answer put into the equation and display the next answer, it should continuing doing this till the value indicate on the loop.

At the moment this is my code:

const pw= (x) =>{
    sum = []
    for(let i=0; i<5; i++){
    let a = (x*x*x)
    sum+= ((4-a)/10)
        
    }
    return sum
    
}

So if I put in 0 the answer is 0.4, then it should take that answer (0.4) automatically put it through the code and return the next answer which is 0.3 and so on.

At the moment that’s where i’m stuck i dont know how to automatically put the next vaule in.
Any guidance will be appreachiated.

console.log(pw(0))
(0.4)
(0.3)
(0.3973)
(0.3937287271683)

2

Answers


  1. You can use a recursive function like this. This will get you your required answer.

    function pw(num, times){
        const sum = (4 - (num ** 3)) / 10;
        console.log(sum);
        if(times<=1) return;
        else pw(sum, times-1);
    }
    
    pw(0, 5);
    

    OR

    If you want to use for loop.

    function pw(num, times){
        for(let i=0;i<5;i++){
            num = (4 - (num ** 3)) / 10;
            console.log(num);
        }
    }
    
    pw(0, 5);
    
    Login or Signup to reply.
  2. If you really must do it recursively, then you can do something like

    const pw = (x, sum=[]) => {
      if (sum.length > 4) {
        return sum;
      }
      let a = (4 - (x * x * x)) / 10;
      return pw(a, [...sum, a]);
    }
    console.log(pw(0))

    Though, that’s not very good, since if you pass in a second argument it goes boom – so, another recursive way

    const pw = input => {
      const fn = (x, sum=[]) => {
        if (sum.length > 4) {
          return sum;
        }
        let a = (4 - (x * x * x)) / 10;
        return fn(a, [...sum, a]);
      }
      return fn(input);
    }
    console.log(pw(0))

    However, no need for recursion at all

    const pw = (x) => {
      const sum = [];
      for (let i = 0; i < 5; ++i) {
        const a = (4 - (x * x * x)) / 10;
        sum.push(a);
        x = a;
      }
      return sum;
    }
    console.log(pw(0))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search