Skip to content

Commit

Permalink
Added Collatz Conjecture
Browse files Browse the repository at this point in the history
  • Loading branch information
zhabinka committed Jan 21, 2019
1 parent a8d0f4e commit bea72d0
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
22 changes: 22 additions & 0 deletions javascript/collatz-conjecture/collatz-conjecture.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// If n is even, divide n by 2 to get n / 2.
// If n is odd, multiply n by 3 and add 1 to get 3n + 1.

const operation = n => (n % 2 === 0 ? n / 2 : 3 * n + 1);

const steps = (number) => {
if (number <= 0) {
throw new Error('Only positive numbers are allowed');
}

const iter = (num, count) => {
if (num === 1) {
return count;
}

return iter(operation(num), count + 1);
};

return iter(number, 0);
};

export { steps };
31 changes: 31 additions & 0 deletions javascript/collatz-conjecture/collatz-conjecture.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { steps } from './collatz-conjecture';

describe('steps()', () => {
test('zero steps for one', () => {
expect(steps(1)).toEqual(0);
});

test('divide if even', () => {
expect(steps(16)).toEqual(4);
});

test('even and odd steps', () => {
expect(steps(12)).toEqual(9);
});

test('Large number of even and odd steps', () => {
expect(steps(1000000)).toEqual(152);
});

test('zero is an error', () => {
expect(() => {
steps(0);
}).toThrow(new Error('Only positive numbers are allowed'));
});

test('negative value is an error', () => {
expect(() => {
steps(-15);
}).toThrow(new Error('Only positive numbers are allowed'));
});
});

0 comments on commit bea72d0

Please sign in to comment.