【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:2つの配列の中で最大の同じ要素
  • を求めます.
  • @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 
    */