diff --git a/src/main/java/com/thealgorithms/maths/LinearEquation.java b/src/main/java/com/thealgorithms/maths/LinearEquation.java new file mode 100644 index 000000000000..407b63a45a71 --- /dev/null +++ b/src/main/java/com/thealgorithms/maths/LinearEquation.java @@ -0,0 +1,27 @@ +package com.thealgorithms.maths; + +/** + * Solves linear equations of the form ax + b = 0. + * + * @see Linear equation (Wikipedia) + */ +public final class LinearEquation { + + private LinearEquation() { + } + + /** + * Solves the equation ax + b = 0 and returns the value of x. + * + * @param a the coefficient of x, must not be zero + * @param b the constant term + * @return the value of x that satisfies the equation + * @throws IllegalArgumentException if a is zero + */ + public static double solve(final double a, final double b) { + if (a == 0) { + throw new IllegalArgumentException("Coefficient 'a' must not be zero"); + } + return -b / a; + } +} diff --git a/src/test/java/com/thealgorithms/maths/LinearEquationTest.java b/src/test/java/com/thealgorithms/maths/LinearEquationTest.java new file mode 100644 index 000000000000..d6ef64ead47b --- /dev/null +++ b/src/test/java/com/thealgorithms/maths/LinearEquationTest.java @@ -0,0 +1,35 @@ +package com.thealgorithms.maths; + +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +class LinearEquationTest { + + @Test + void testSolveBasic() { + assertEquals(3.0, LinearEquation.solve(2, -6)); + } + + @Test + void testSolveNegativeResult() { + assertEquals(-5.0, LinearEquation.solve(1, 5)); + } + + @Test + void testSolveWithZeroB() { + assertEquals(0.0, LinearEquation.solve(4, 0), 1e-9); + } + + @Test + void testSolveWithNegativeA() { + assertEquals(3.0, LinearEquation.solve(-3, 9)); + } + + @Test + void testAllIllegalInput() { + assertAll(() -> assertThrows(IllegalArgumentException.class, () -> LinearEquation.solve(0, 5)), () -> assertThrows(IllegalArgumentException.class, () -> LinearEquation.solve(0, 0)), () -> assertThrows(IllegalArgumentException.class, () -> LinearEquation.solve(0, -3))); + } +}