Added getDivisors function

This commit is contained in:
2021-03-26 13:27:47 -04:00
parent 879fdfd126
commit 6443a56de8
2 changed files with 97 additions and 1 deletions

View File

@@ -389,6 +389,85 @@ export function getFactorsBig(goalNumber: bigint): bigint[]{
return factors;
}
export function getDivisors(goalNumber: number): number[]{
let divisors: number[] = [];
//Start by checking that the number is positive
if(goalNumber <= 0){
return divisors;
}
//If the number is 1 return just itself
else if(goalNumber == 1){
divisors.push(1);
return divisors;
}
//Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly
let topPossibleDivisor: number = Math.ceil(Math.sqrt(goalNumber));
for(let possibleDivisor = 1;possibleDivisor <= topPossibleDivisor;++possibleDivisor){
//If you find one add it and the number it creates to the list
if((goalNumber % possibleDivisor) == 0){
divisors.push(possibleDivisor);
//Account for the possibility of sqrt(goalNumber) being a divisor
if(possibleDivisor != topPossibleDivisor){
divisors.push(goalNumber / possibleDivisor);
}
if(divisors[divisors.length - 1] == (possibleDivisor + 1)){
++possibleDivisor;
}
}
}
//Sort the list before returning it for neatness
divisors.sort((a, b) => a - b);
//Return the list
return divisors;
}
export function getDivisorsBig(goalNumber: bigint): bigint[]{
let divisors: bigint[] = [];
//Start by checking that the number is positive
if(goalNumber <= 0n){
return divisors;
}
//If the number is 1 return just itself
else if(goalNumber == 1n){
divisors.push(1n);
return divisors;
}
//Start at 3 and loop through all numbers < sqrt(goalNumber) looking for a number that divides it evenly
let topPossibleDivisor: bigint = sqrtBig(goalNumber);
for(let possibleDivisor = 1n;possibleDivisor <= topPossibleDivisor;++possibleDivisor){
//If you find one add it and the number it creates to the list
if((goalNumber % possibleDivisor) == 0n){
divisors.push(possibleDivisor);
//Account for the possibility of sqrt(goalNumber) being a divisors
if(possibleDivisor != topPossibleDivisor){
divisors.push(goalNumber / possibleDivisor);
}
if(divisors[divisors.length - 1] == (possibleDivisor + 1n)){
++possibleDivisor;
}
}
}
//Sort the list before returning it for neatness
divisors.sort((a, b) => {
if(a > b){
return 1;
}
else if(a < b){
return -1;
}
else{
return 0;
}
});
//Return the list
return divisors;
}
export function getSum(ary: number[]): number{
let sum: number = 0;
ary.forEach(a => sum += a);