Created
October 28, 2013 02:06
-
-
Save KenjiOhtsuka/7190370 to your computer and use it in GitHub Desktop.
素因数分解
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
素因数分解をするだけのコード | |
もっと効率的な方法があれば知りたいです。 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form> | |
調査する数 <input type="text" style="text-align:right;" id="TargetNumber" value="48" /><input type="button" onclick="calculate(document.getElementById('TargetNumber').value);" value="計算する" /> <br /> | |
素因数分解の結果 <input type="text" id="PrimeFactorDecomposition" /><br /> | |
約数の数 <input type="text" id="DivisorsCount" style="text-align:right;" /> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function calculate(value) { | |
if (!isValidInput(value)) { | |
alert('数値は2以上の整数を入力してください。'); | |
return; | |
} | |
var elements = getPrimeFactorArray(value); | |
document.getElementById('DivisorsCount').value = | |
getDivisorsCount(elements); | |
document.getElementById('PrimeFactorDecomposition').value = | |
getPrimeFactorDecomposition(elements); | |
} | |
function isValidInput(value) { | |
if (value.match(/^[1-9]\d*$/) && value > 1) { | |
return true; | |
} else { | |
return false; | |
} | |
} | |
function getPrimeFactorArray(plusNumber) { | |
var targetNumber = plusNumber; | |
var count = 0; | |
var elements = new Array(); | |
for (var i = 0, divisor = 2; divisor <= targetNumber / divisor; i++, divisor = 2 * i + 1) { | |
while (1) { | |
if (targetNumber % divisor === 0) { | |
targetNumber /= divisor; | |
count++; | |
} else { | |
if (count != 0) { | |
elements.push([divisor, count]); | |
count = 0; | |
} | |
break; | |
} | |
} | |
} | |
if (targetNumber != 1) { | |
elements.push([targetNumber, 1]); | |
} | |
return elements; | |
} | |
function getPrimeFactorDecomposition(elements) { | |
var resultString = ''; | |
for (var i = 0; i < elements.length; i++) { | |
resultString += ('*' + elements[i][0].toString()); | |
if (elements[i][1] != 1) { | |
resultString += ('^' + elements[i][1].toString()); | |
} | |
} | |
return resultString.substr(1); | |
} | |
function getDivisorsCount(elements) { | |
var resultCount = 1; | |
for (var i = 0; i < elements.length; i++) { | |
resultCount *= (1 + elements[i][1]); | |
} | |
return resultCount; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment