Recursions

by Mehmetcan Sinir

JavaScript

fa
it opens upp all the recursive functions necessary like 1,2,3,4,5,6,7 and closes them in the reverse order 7,6,5,4,3,2,1*/


//factorial function
function factorial(a) {
    if (a === 3) {
        return a * (a - 1);
    } else {
        return a * factorial(a - 1);
    }
}
console.log(factorial(5));


//find greatest common divisor
function gcd(first, second) {
    if (!second) {
        return first;
    }
    return gcd(second, first % second);
}

console.log(gcd(300, 1300));

/*gcd(40 15)
gcd(15,10)
gcd(10, 5) 
gcd(5, 0)
*/

//Write a JavaScript program to get the integers in range (x, y).

function range(start, end) {
    if (end - start === 2) {
        return [start + 1];
    } else {
        var list = range(start, end - 1);
        list.push(end - 1);
        return list;
    }
}

console.log(range(3, 8));

//Write a JavaScript program to compute the sum of an array of integers.

function sum(array) {
    if (array.length === 1) {
        return array[0];
    } else {
        var end = array.pop();
        var total = sum(array);
        total += end;
        return total;
    }
}

console.log(sum([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]));