Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 741da8d

Browse files
author
programmiri
committed
Solve exercise Collatz Conjecture
1 parent ce6856a commit 741da8d

File tree

2 files changed

+33
-5
lines changed

2 files changed

+33
-5
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
function divideByTwo(num) {
2+
return num / 2;
3+
}
4+
5+
function multiplyByThreeAddOne(num) {
6+
return num * 3 + 1;
7+
}
8+
9+
function steps(number) {
10+
if (number <= 0) {
11+
throw new Error('Only positive numbers are allowed');
12+
}
13+
14+
let currNumber = number;
15+
let count = 0;
16+
while (currNumber !== 1) {
17+
if (currNumber % 2 === 0) {
18+
currNumber = divideByTwo(currNumber);
19+
} else {
20+
currNumber = multiplyByThreeAddOne(currNumber);
21+
}
22+
23+
count++;
24+
}
25+
return count;
26+
}
27+
28+
export { steps };

‎collatz-conjecture/collatz-conjecture.spec.js‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,25 +5,25 @@ describe('steps()', () => {
55
expect(steps(1)).toEqual(0);
66
});
77

8-
xtest('divide if even', () => {
8+
test('divide if even', () => {
99
expect(steps(16)).toEqual(4);
1010
});
1111

12-
xtest('even and odd steps', () => {
12+
test('even and odd steps', () => {
1313
expect(steps(12)).toEqual(9);
1414
});
1515

16-
xtest('Large number of even and odd steps', () => {
16+
test('Large number of even and odd steps', () => {
1717
expect(steps(1000000)).toEqual(152);
1818
});
1919

20-
xtest('zero is an error', () => {
20+
test('zero is an error', () => {
2121
expect(() => {
2222
steps(0);
2323
}).toThrow(new Error('Only positive numbers are allowed'));
2424
});
2525

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

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /