【JavaScript基础算法总结篇(一)】阶乘之和 */* 因子数组 */* 数组最大相同元素 */* 1~100间所有3的倍数之和 */* 九九乘法表

  • @No.1
  • @description:计算1到该数的阶乘之和
  • @input:
    5
  • @output:
    153
var num = 5;
var result = 0;
while(num > 0){
    var mid = 1;
    var a = num;
    while(a > 0){
        mid *= a;
        a--;
    };
    result += mid;
    num--;
};
console.log(result);

/**
*@OUTPUT
153
*/
  • @No.2
  • @description:求一个数的所有因子,返回所有因子组成的数组(升序)
  • @input:
    12
  • @output:
    [ 1, 2, 3, 4, 6, 12 ]
function maxNum(num){
    var arr = [];
    for(var i = 1;i<num;i++){
        if(num%i == 0){
            arr.push(i);
        };
    };
    return arr.sort((a, b) => a - b);
};
console.log(maxNum(180));

/**
*@OUTPUT
[ 1,  2,  3,  4,  5,  6,  9, 10, 12, 15, 18, 20, 30, 36, 45, 60, 90 ]
*/
  • @No.3
  • @description:求出两个数组中最大的相同元素
  • @input:
    [ 1, 2, 3, 4, 6, 12 ]
    [ 1, 2, 4, 8 ]
  • @output:
    4
function compareMax(arr1,arr2){
    for(var a = arr1.length-1;a>=0;a--){
        for(var b = arr2.length-1;b>=0;b--){
            if(arr1[a] == arr2[b]){
                return arr1[a];
            };
        };
    };
};
console.log(compareMax([ 1, 2, 3, 4, 6, 12 ],[ 1, 2, 4, 8 ]));

/**
*@OUTPUT
4
*/
  • @No.4
  • @description:计算1-100之间所有3的倍数之和
  • @input:
    100
  • @output:
    1683
var num = 100;
var result = 0;
for(var i=0;i<num;i++){
    if(i%3 == 0){
        result += i;
    };
};
console.log(result);

/**
*@OUTPUT
1683
*/
  • @No.5
  • @description:九九乘法表
  • @input:
  • @output:
for(var i = 1;i<=9;i++){
    var num = " ";
    for(var j = 1;j<=i;j++){
        num +=(j + " * " + i + " = " + i*j) + (i*j >9?" ":"  ");
    };
    console.log(num);
};

/**
*@OUTPUT
 1 * 1 = 1 
 1 * 2 = 2  2 * 2 = 4  
 1 * 3 = 3  2 * 3 = 6  3 * 3 = 9  
 1 * 4 = 4  2 * 4 = 8  3 * 4 = 12 4 * 4 = 16 
 1 * 5 = 5  2 * 5 = 10 3 * 5 = 15 4 * 5 = 20 5 * 5 = 25 
 1 * 6 = 6  2 * 6 = 12 3 * 6 = 18 4 * 6 = 24 5 * 6 = 30 6 * 6 = 36 
 1 * 7 = 7  2 * 7 = 14 3 * 7 = 21 4 * 7 = 28 5 * 7 = 35 6 * 7 = 42 7 * 7 = 49 
 1 * 8 = 8  2 * 8 = 16 3 * 8 = 24 4 * 8 = 32 5 * 8 = 40 6 * 8 = 48 7 * 8 = 56 8 * 8 = 64 
 1 * 9 = 9  2 * 9 = 18 3 * 9 = 27 4 * 9 = 36 5 * 9 = 45 6 * 9 = 54 7 * 9 = 63 8 * 9 = 72 9 * 9 = 81 
*/

你可能感兴趣的:(JavaScript,javascript,算法)