Tính các thừa số của một số nguyên dương
Mã nguồn:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Compute the factors of a positive integer</title>
<script>
function factors(n)
{
var num_factors = [], i;
for (i = 1; i <= Math.floor(Math.sqrt(n)); i += 1)
if (n % i === 0)
{
num_factors.push(i);
if (n / i !== i)
num_factors.push(n / i);
}
num_factors.sort(function(x, y)
{
return x - y;}); // numeric sort
return num_factors;
}
document.write(factors(15)); // [1,3,5,15]
document.write(factors(16)); // [1,2,4,8,16]
document.write(factors(17)); // [1,17]
</script>
</head>
<body>
</body>
</html>
hiepsiihtml1
Lưu đồ thuật toán:

Thấy bài viết hữu ích?
Ủng hộ tác giả để có thêm nhiều bài viết chất lượng nhé!