Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

algorithm: quadratic formula #1151

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions DIRECTORY.md
Original file line number Diff line number Diff line change
@@ -193,6 +193,7 @@
* [PowLogarithmic](Maths/PowLogarithmic.js)
* [PrimeCheck](Maths/PrimeCheck.js)
* [PrimeFactors](Maths/PrimeFactors.js)
* [QuadraticFormula](Maths/QuadraticFormula.js)
* [RadianToDegree](Maths/RadianToDegree.js)
* [ReverseNumber](Maths/ReverseNumber.js)
* [ReversePolishNotation](Maths/ReversePolishNotation.js)
32 changes: 32 additions & 0 deletions Maths/QuadraticFormula.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* @function quadraticFormula
* @description This script will find the the roots of a quadratic equation.
* @param {number} a
* @param {number} b
* @param {number} c
* @return {array}
* @see https://en.wikipedia.org/wiki/Quadratic_formula
* @example quadraticFormula(1, -3, -4) = [4, -1]
* @example quadraticFormula(1, 5, 6) = [-2, -3]
* @example quadraticFormula(1, -3, 8) = []
*/

const solveQuadraticEquation = (a, b, c) => {
if (typeof a !== 'number' || typeof b !== 'number' || typeof c !== 'number') {
return new TypeError('Some argument is not a number.')
}
const discriminant = (b ** 2) - (4 * a * c)
const denominator = 2 * a
let answer = []
if (discriminant > 0) {
const x1 = (-b + Math.sqrt(discriminant)) / denominator
const x2 = (-b - Math.sqrt(discriminant)) / denominator
answer = [x1, x2]
} else if (discriminant === 0) {
const x = (-b) / denominator
answer = [x]
}
return answer
}

export { solveQuadraticEquation }
9 changes: 9 additions & 0 deletions Maths/test/QuadraticFormula.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { solveQuadraticEquation } from '../QuadraticFormula'

test('Quadratic Equation', () => {
expect(solveQuadraticEquation(1, -3, -4)).toStrictEqual([4, -1])
expect(solveQuadraticEquation(1, 5, 6)).toStrictEqual([-2, -3])
expect(solveQuadraticEquation(3, 24, 48)).toStrictEqual([-4])
expect(solveQuadraticEquation(1, -3, 8)).toStrictEqual([])
expect(solveQuadraticEquation(1, -2, 9)).toStrictEqual([])
})
11,186 changes: 7 additions & 11,179 deletions package-lock.json

Large diffs are not rendered by default.