Minor fixes. (#91)

* Get Bit: Make more terse

* Power of two: Allowed 1 as a valid power of 2.
Power of two: Removed unnecessary exception throwing.

* Fisher Yates: Made more terse

* Least Common Multiple: Fill undefined value

* Greatest Common Divisor: Fill undefined value.
Greatest Common Divisor: Make more terse.
This commit is contained in:
Bruce-Feldman
2018-07-04 10:53:22 -04:00
committed by Oleksii Trekhleb
parent 93bfe97e27
commit e36c441fa9
10 changed files with 15 additions and 75 deletions

View File

@ -2,7 +2,7 @@ import euclideanAlgorithm from '../euclideanAlgorithm';
describe('euclideanAlgorithm', () => {
it('should calculate GCD', () => {
expect(euclideanAlgorithm(0, 0)).toBeNull();
expect(euclideanAlgorithm(0, 0)).toBe(0);
expect(euclideanAlgorithm(2, 0)).toBe(2);
expect(euclideanAlgorithm(0, 2)).toBe(2);
expect(euclideanAlgorithm(1, 2)).toBe(1);

View File

@ -1,32 +1,11 @@
/**
* @param {number} originalA
* @param {number} originalB
* @return {number|null}
* @return {number}
*/
export default function euclideanAlgorithm(originalA, originalB) {
const a = Math.abs(originalA);
const b = Math.abs(originalB);
if (a === 0 && b === 0) {
return null;
}
if (a === 0 && b !== 0) {
return b;
}
if (a !== 0 && b === 0) {
return a;
}
// Normally we need to do subtraction (a - b) but to prevent
// recursion occurs to often we may shorten subtraction to (a % b).
// Since (a % b) is normally means that we've subtracted b from a
// many times until the difference became less then a.
if (a > b) {
return euclideanAlgorithm(a % b, b);
}
return euclideanAlgorithm(b % a, a);
return (b === 0) ? a : euclideanAlgorithm(b, a % b);
}