Skip to content

Commit c671eae

Browse files
committed
BAEL-9247 How to Check if a Number Is the Sum of Two or More Consecutive Integers
1 parent 3e87a5d commit c671eae

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package com.baeldung.algorithms.consecutivenumbers;
2+
3+
import org.junit.jupiter.api.Test;
4+
import static org.junit.jupiter.api.Assertions.assertTrue;
5+
6+
public class ConsecutiveNumbersUnitTest {
7+
8+
@Test
9+
void whenIsSumOfConsecutiveUsingBruteForce_thenReturnsTrue() {
10+
int n = 15;
11+
12+
boolean isSumOfConsecutive = false;
13+
for (int k = 2; (k * (k - 1)) / 2 < n; k++) {
14+
int diff = n - k * (k - 1) / 2;
15+
if (diff % k == 0 && diff / k > 0) {
16+
isSumOfConsecutive = true;
17+
break;
18+
}
19+
}
20+
21+
assertTrue(isSumOfConsecutive);
22+
}
23+
24+
@Test
25+
void whenIsSumOfConsecutiveUsingBitwise_thenReturnsTrue() {
26+
int n = 15;
27+
boolean result = (n > 0) && ((n & (n - 1)) != 0);
28+
assertTrue(result);
29+
}
30+
31+
}

0 commit comments

Comments
 (0)