在Javascript中对一个数字进行分解

时间:2017-02-09 11:07:11

标签: javascript c++ prime-factoring factorization

我学会了一种用C ++和Java分解数字的算法,现在决定"翻译"它变成了JS。这是我的代码:

<!DOCTYPE HTML>
<html>
 <head>
  <title>Factorization</title>
  <script>
 function fact(num)
 {
    var b = 2;
    while (num > b){
    while(num%b==0){
    num/=b;
    return b;
    }
    b++;
    if(num==b){
    return b;
    }
    }
 }
  </script>
 </head>

 <body>
 <form name="f1">
  Enter the Number  :<input type="number" name="txt1"><br>
  <input type="button" value="Factorize" onclick="alert('The answer is ' + fact(txt1.value))">
  </form>
 </body>
</html>

有什么问题吗?它只提醒第一个倍数。

P / S C ++中的工作算法是:

#include<iostream>
using namespace std;

int main(){
    int a;
    cin >> a;
    int b=2;
    while(a>b){
        while(a%b==0){
            a/=b;
            cout << b << endl;
        }
        b++;
        if(a==b){
            cout << b << endl;
        }
    }
}

2 个答案:

答案 0 :(得分:2)

您正在退出该功能的第一个倍数。您可以查看以下代码,它会对您有所帮助。

function fact(num)
 {
    var b = 2;
	var factors =1;
	if(num==b){
      return b;
    }
    while (num > b){
      if(num % b == 0)
	  {
		 factors +=','+b;
	  }
	b++;
   }
   factors +=','+num;
   return factors;
 }
 <form name="f1">
  Enter the Number  :<input type="number" name="txt1"><br>
  <input type="button" value="Factorize" onclick="alert('The answer is ' + fact(txt1.value))">
  </form>

答案 1 :(得分:1)

如@Blaze Sahlzen所指出的,return语句退出函数,考虑构造并返回一个字符串:

function fact(num)
{
    let b = 2;
    let ans = "\n";
    while (num > b){
        while(num%b==0){
            num/=b;
            ans += b + '\n';
        }
        b++;
        if(num==b){
            ans += b + '\n';
        }
    }
    return ans;
}