Skip to content

Commit 75434a8

Browse files
Add LinearEquation to maths
1 parent 9729e56 commit 75434a8

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package com.thealgorithms.maths;
2+
3+
/**
4+
* Solves linear equations of the form ax + b = 0.
5+
*/
6+
public final class LinearEquation {
7+
8+
private LinearEquation() {
9+
}
10+
11+
/**
12+
* Solves the equation ax + b = 0 and returns the value of x.
13+
*
14+
* @param a the coefficient of x, must not be zero
15+
* @param b the constant term
16+
* @return the value of x that satisfies the equation
17+
* @throws IllegalArgumentException if a is zero
18+
*/
19+
public static double solve(final double a, final double b) {
20+
if (a == 0) {
21+
throw new IllegalArgumentException("Coefficient 'a' must not be zero");
22+
}
23+
return -b / a;
24+
}
25+
}
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.thealgorithms.maths;
2+
3+
import static org.junit.jupiter.api.Assertions.assertAll;
4+
import static org.junit.jupiter.api.Assertions.assertEquals;
5+
import static org.junit.jupiter.api.Assertions.assertThrows;
6+
7+
import org.junit.jupiter.api.Test;
8+
9+
class LinearEquationTest {
10+
11+
@Test
12+
void testSolveBasic() {
13+
assertEquals(3.0, LinearEquation.solve(2, -6));
14+
}
15+
16+
@Test
17+
void testSolveNegativeResult() {
18+
assertEquals(-5.0, LinearEquation.solve(1, 5));
19+
}
20+
21+
@Test
22+
void testSolveWithZeroB() {
23+
assertEquals(0.0, LinearEquation.solve(4, 0), 1e-9);
24+
}
25+
26+
@Test
27+
void testSolveWithNegativeA() {
28+
assertEquals(3.0, LinearEquation.solve(-3, 9));
29+
}
30+
31+
@Test
32+
void testAllIllegalInput() {
33+
assertAll(
34+
() -> assertThrows(IllegalArgumentException.class, () -> LinearEquation.solve(0, 5)),
35+
() -> assertThrows(IllegalArgumentException.class, () -> LinearEquation.solve(0, 0)),
36+
() -> assertThrows(IllegalArgumentException.class, () -> LinearEquation.solve(0, -3))
37+
);
38+
}
39+
}

0 commit comments

Comments
 (0)