Js Recursive Sum 1, 2, 2, 3, 1, 2, 3, 3, 2, 3, 3, 2, 3, 2, 3, 2, 1?

js Recursive Sum 1, 2, 3, 3, 3, 3, 3, 3, 2, 1?

Feb.27,2021

there are actually all the answers upstairs, but the title requires recursion.
Recursive bar. My understanding is to try to avoid any transformation process and use your brain as little as possible, right?
I will mainly talk about the train of thought of solving this kind of problem. The idea of
recursion is to solve the problem in stages and then determine the end point. The core of
is to find the relationship between fn (n) and fn (nMui 1). Combined with the boundary condition fn (1), write a function as follows:

function fn(n) {
    // 
    if (...) return ...;
    // 
    return fn(n-1) + ...;
}

for this question,

fn(n) = 1 + 2 + 3 + ... + n-1 + n + n-1 + ... + 3 + 2 + 1;
fn(n-1) = 1 + 2 + 3 + ... + n-1 + ... + 3 + 2 + 1;

so

fn(n) = fn(n-1) + n-1 + n;

end point

fn(1) = 1;

can be combined to write

.
function fn(n) {
    if (n==1) return 1; // 
    return fn(n-1) + n-1 + n; // 
}

similar ones can be obtained in the same way


define f (n) = sum (1, 2, 3,., n,., 3, 2, 1) .

< H2 > solution one < / H2 > The

problem translates into f (n) = 2 * g (n)-n , where g (n) = sum (1,2,3,., n) ). If we do not use Gaussian summation to force recursion, g (n) = g (n-1) + n (n > 1), g (n) = 1 (n = 1).

function g(n) {
  if(n > 1) return g(n - 1) + n;
  else if(n == 1) return 1;
}

function f(n) {
  return 2 * g(n) + n;
}
< H2 > solution II < / H2 >

obviously, f (n) = f (n-1) + n + (n-1) (n > 1), f (n) = 1 (n = 1).

function f(n) {
  if(n > 1) return f(n - 1) + n + n - 1;
  else if(n == 1) return 1;
}

var a = 1;
for (var i = 2; i < n; iPP) {
    a = a + i
}
var sum = 2*a + n;
console.log(sum)

transform 1 n into the sum of the former n terms and n terms.
thus comes
1 + 2 + 3 + 4 +. + n +. + 3 + 2 + 1 = n (n + 1) / 2 + (n-1) (n-1 + 1) / 2
to get n < sup > 2 < / sup >

so:


<br>4<br> indexPP<br>value = 1+2+3+4 <br> return;<br> index--<br>value += 3+2+1+0;<br>var cal = function() {

        var index=0;
        var value=0;
        return function show(n) {
                if(n < 0) return;
                value += index;
                if(index === n)return;
                indexPP; 
                show(n);
                index--;
                value += index;
                return value;
        }
    };
    cal()(4) // 16
    
MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1b32341-2bdf0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1b32341-2bdf0.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?