Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions src/main/java/com/thealgorithms/maths/LinearEquation.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.thealgorithms.maths;

/**
* Solves linear equations of the form ax + b = 0.
*
* @see <a href="https://en.wikipedia.org/wiki/Linear_equation">Linear equation (Wikipedia)</a>
*/
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;
}
}
35 changes: 35 additions & 0 deletions src/test/java/com/thealgorithms/maths/LinearEquationTest.java
Original file line number Diff line number Diff line change
@@ -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)));
}
}
Loading