Problem Statement: List all divisors of a positive whole number.
e.g.
Input:
n=27
Output:
divisors=[1,3,9,27]
Solution 1( Upper bound of loop is sqrt(num) ):
let num = 27;
/*
Even numbers can have odd divisors
Odd number can't have even divisors
*/
function getAllDivisors(num) {
let result = [];
if (num == 1) {
return [1];
} else {
let max = Math.sqrt(num);
let isOdd = num % 2; //for odd number reminder 1
let i = 1;
while (i <= max) {
if (num % i == 0) {
result.push(i);
/*if is square root then it will get added twice
we want a divisor to be added once once*/
if (num / i != i) {
result.push(num/i);
}
}
if (isOdd == 1) {
i += 2;
} else {
i++;
}
}
return result;
}
}
let allDivisiors = getAllDivisors(num);
console.log(allDivisiors)
Output:
[ 1, 27, 3, 9 ]
Solution 2( Upper bound of loop is num/2 ):
let num = 27;
/*
Even numbers can have odd divisors
Odd number can't have even divisor
*/
function getAllDivisors(num) {
let result = [];
if (num == 1) {
return [1];
} else {
let max = Math.floor(num / 2);
let isOdd = num % 2; //for odd number reminder 1
let i = 1;
while (i <= max) {
if (num % i == 0) {
result.push(i);
}
if (isOdd == 1) {
i += 2;
} else {
i++;
}
}
//every number divides itself
result.push(num);
return result;
}
}
let allDivisiors = getAllDivisors(num);
console.log(allDivisiors);
Output:
[ 1, 27, 3, 9 ]
No comments:
Post a Comment