从行尾删除逗号并确定素数因子和因子

时间:2016-02-25 10:51:28

标签: javascript

我想列出两组数字的所有因素和素数因素。

这是我的代码,但我的主要因素不对,并且不需要行末的逗号。

任何纠正素因子的帮助? 4应该是2,2,2但它应该是2。

var l = parseInt(prompt("What is your lowest number"));
var k = parseInt(prompt("What is your highest number"));
var results = '';

//function counts (incremental) the numbers
// display the numbers in bold
// numbers are display on the left of

    function genFactors(num) {
    var result = "";
    var result1 = "";

    for (var i = 2; i <= num; ++i) {
        if (num % i == 0) {
            result += i + ",";
            result1 += genPrimeFactors(i);
        }
    }
    results += '<b>' + num + '</b>: ' + result1 + '<br>';

    return result;
    }

    document.writeln("<h1>All Factors</h1>");
    document.writeln("<p>The factors of " + l + " and " + k + " are: " + ":      
    </p>");

    for (var num = 1; num <= k; ++num) {
    document.writeln("<b>" + num + "</b>" + ":" + genFactors(num) + "<br />");
   }
//  determine the prime numbers


    function isPrime(num) {
    for (var i = 2; i < num; i++) {
        if (num % i === 0) {
            return 0;
        } else {
            return 1;
        }
    }
    }
//determine the prime factors

     function genPrimeFactors(num) {
     for (var i = 2; i <= num; i++) {
        if (num % i != 0) {
            while ((num / 2 == parseInt(num / 2)) && (num > 2)) {
                num = num / 2;
                return "";
            }
            if (isPrime(num)) {
                return num + ',';
            } else {

            }
        }
      }
      if (num == 2) {
        return 2 + ',';
    }
    }

/*function 
    function genPrimeFactors(num) {
    var result = "";

    for (var i = 2; i <= num; ++i) {
        for (var k = 2; k <= i; ++k) {
            if (i % k != 0) {
            }
            result += i + ",";
        }

    }
    return result;
}
*/output

    document.writeln("<h1>Prime Factors</h1>");
    document.writeln("<p>The prime factors of " + l + " and " + k + " are: " + ":</p>");
   document.writeln(results);

1 个答案:

答案 0 :(得分:0)

您可以在返回时使用子字符串剪切逗号,如下所示

function genFactors(num) {
 var result = "";
 var result1 = "";

 for (var i = 2; i <= num; ++i) {
     if (num % i == 0) {
         result += i + ",";
         result1 += genPrimeFactors(i);
     }
 }
 result1.substring(0,result1.length-1);//maybe try this
 results += '<b>' + num + '</b>: ' + result1 + '<br>';

 return result.substring(0,result.length-1);
}