Fixed combinations

This commit is contained in:
Arthur Guiot
2023-09-23 16:34:55 -07:00
parent 50826f9af8
commit 6cf9675a56
2 changed files with 3 additions and 3 deletions
@@ -31,7 +31,7 @@ public func permutationsWithRepitition(_ n: Int, _ k: Int) -> BigInt {
public func combinationsWithRepetitions(_ n: Int, _ k: Int) throws -> BigInt { public func combinationsWithRepetitions(_ n: Int, _ k: Int) throws -> BigInt {
// (n + k - 1)! / (k! * (n - 1)!) // (n + k - 1)! / (k! * (n - 1)!)
guard k != 0 && n != 1 else { throw EulerError.DivisionByZero } guard k != 0 && n != 1 else { throw EulerError.DivisionByZero }
return try factorial(BigInt(n + k - 1)) / factorial(BigInt(k)) * factorial(BigInt(n - 1)) return try factorial(BigInt(n + k - 1)) / (factorial(BigInt(k)) * factorial(BigInt(n - 1)))
} }
/// Combinations: `$\frac{n!}{k! * (n - k)!}$`. /// Combinations: `$\frac{n!}{k! * (n - k)!}$`.
@@ -42,5 +42,5 @@ public func combinationsWithRepetitions(_ n: Int, _ k: Int) throws -> BigInt {
public func combinations(_ n: Int, _ k: Int) throws -> BigInt { public func combinations(_ n: Int, _ k: Int) throws -> BigInt {
// n! / (k! * (n - k)!) // n! / (k! * (n - k)!)
guard n - k != 0 else { throw EulerError.DivisionByZero } guard n - k != 0 else { throw EulerError.DivisionByZero }
return try factorial(BigInt(n)) / factorial(BigInt(k)) * factorial(BigInt(n - k)) return try factorial(BigInt(n)) / (factorial(BigInt(k)) * factorial(BigInt(n - k)))
} }
+1 -1
View File
@@ -11,7 +11,7 @@ class TablesTests: XCTestCase {
func testCommon() { func testCommon() {
let t = Tables() let t = Tables()
XCTAssertEqual(t.ABS(-2), 2) XCTAssertEqual(t.ABS(-2), 2)
XCTAssertEqual(try t.COMBIN(5, k: 3), 40) XCTAssertEqual(try t.COMBIN(5, k: 3), 10)
XCTAssertEqual(t.DECIMAL("ff", 16), 255) XCTAssertEqual(t.DECIMAL("ff", 16), 255)
XCTAssert(t.DEGREES(pi / 2).nearlyEquals(90)) XCTAssert(t.DEGREES(pi / 2).nearlyEquals(90))
XCTAssertEqual(try t.FACTDOUBLE(6).scientificDescription, "2.6012×10¹⁷⁴⁶") XCTAssertEqual(try t.FACTDOUBLE(6).scientificDescription, "2.6012×10¹⁷⁴⁶")