{"id":19093854,"url":"https://github.com/mussacharles/maths-for-fast-algorithms","last_synced_at":"2026-03-01T02:02:30.339Z","repository":{"id":41998995,"uuid":"476919866","full_name":"MussaCharles/maths-for-fast-algorithms","owner":"MussaCharles","description":"Detailed explanations and implementations of various maths concepts for writing high performance code/algorithms backed with Unit tests.","archived":false,"fork":false,"pushed_at":"2022-11-26T01:40:33.000Z","size":52,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-09-08T00:40:57.142Z","etag":null,"topics":["algorithms","data-structures","maths","swift-algorithms"],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/MussaCharles.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"docs/CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-04-02T01:54:52.000Z","updated_at":"2024-03-13T17:20:53.000Z","dependencies_parsed_at":"2023-01-21T21:49:37.954Z","dependency_job_id":null,"html_url":"https://github.com/MussaCharles/maths-for-fast-algorithms","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/MussaCharles/maths-for-fast-algorithms","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MussaCharles%2Fmaths-for-fast-algorithms","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MussaCharles%2Fmaths-for-fast-algorithms/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MussaCharles%2Fmaths-for-fast-algorithms/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MussaCharles%2Fmaths-for-fast-algorithms/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/MussaCharles","download_url":"https://codeload.github.com/MussaCharles/maths-for-fast-algorithms/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/MussaCharles%2Fmaths-for-fast-algorithms/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29958395,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-03-01T01:47:18.291Z","status":"online","status_checked_at":"2026-03-01T02:00:07.437Z","response_time":124,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["algorithms","data-structures","maths","swift-algorithms"],"created_at":"2024-11-09T03:26:22.220Z","updated_at":"2026-03-01T02:02:30.305Z","avatar_url":"https://github.com/MussaCharles.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Maths for fast algorithms\nDetailed explanations and implementations of various maths concepts which can help software Engineers write high performance code/algorithms backed with Unit tests.\n\n**Note:** This repo is a work in progress, [contributions](docs/CONTRIBUTING.md) are highly appreciated. \n\n## Arithmetic Sequence /Arithmetic Progression(AP)\n\n## Theory\nArithmetic Sequence is a sequence of numbers having a common/constant difference.\n\n For example `1,2,3......n` has a common difference (d) of `1`\n\nBy using [Gauss's technic](https://en.wikipedia.org/wiki/Arithmetic_progression) for summing an arithmetic sequence all we need to know is the first term (A\u003csub\u003e1\u003c/sub\u003e) and the common difference (d) Or just the first term, n\u003csup\u003eth\u003c/sup\u003e term and the total number of terms (n).\n\nIn AP the nth term can be calculated as follows: - \n\n `An = A1 + (n-1)d`\n\nThus using that we can have two ways of computing the sum fo the sequence, also known as Arithmetic Series (S\u003csub\u003en\u003c/sub\u003e) as follows: - \n\n`Sn = n/2(A1 + An)`\n\nIf we substitute the value of `An` we can also deduce a second formula as follows: - \n\n  `Sn = n/2[A1 + A1 + (n-1)d]`\n\nTherefore\n\n  `Sn = n/2[2A1 + (n-1)d]`\n\n***Note:** For full derivations of the fomulas above see Suggested Learning Materials [Section.](#suggested-learning-materials)*\n\n## Code Samples \u0026 Complexity Analysis\n\nConsider a list of natural numbers below: - \n\n`1,2,3,4,......................................1,000,000`\n\nUsing the naive approach to find the sum of the numbers would be to iterate through all numbers and add them one by one.\nHere is an example of swift code for the naive approach.\n\nThis approach will given us `O(n)` run time. \n\n### Naive approach Swift sample code, `O(n)`\n\n```swift\nimport Foundation\n\npublic struct NaiveSum {\n\n    public func compute(firstTerm A1: Int, nthTerm n: Int, commonDifference d: Int) -\u003e Int {\n        var allTerms: [Int] = []\n        var currentTerm: Int = A1\n        for _ in 1...n {\n            allTerms.append(currentTerm)\n            currentTerm += d\n        }\n\n        var sum:Int = 0\n        for term in allTerms {\n            sum += term\n        }\n        \n        return sum\n    }\n\n}\n\n```\n\nRecursion example\n```swift\n/// Use recursion to sum `n` arithmetic terms.\n///\n/// - Time Complexity -\u003e O(n)\n/// - Space Complexity -\u003e O(n)\n/// - Parameter n: Number of terms.\n/// - Returns: The sum of the first n terms.\nfunc sum(_ n: Int) -\u003e Int {\n    if n \u003c= 0 {\n        return 0\n    }\n    return n + sum(n - 1)\n}\n```\n\n\n### Gauss's Arithmetic Series sum, `O(1)`\n\nNow let's try using technics for summing an arithmetic sequence to achive `O(1)` time complexity for summing a huge amount of numbers.\n\nA swift implementation for arithmetic sum using Gauss's technic is as follows.\n      \n```swift\nimport Foundation\n\npublic struct GaussSum {\n\n    public func compute(firstTerm a1: Int, nthTerm n: Int, commonDifference d: Int) -\u003e Int {\n       // Sn = n/2 (2A1 + (n - 1)d)\n        let sum =  (2 * a1 + (n - 1) * d) *  n / 2\n        return sum\n    }\n\n}\n\n```\n\n### Unit tests to verify our implementation details\n\n**Note:** Code snippet for this section can be run using Swift Playgrounds.You can find the source code [here.](ArithmeticSequence.playground)\n\n\nLet's write some unit tests for the above two implementations with different data sets, starting from small amount of data to a very large amount.\nWe will try to increase the nth term and see if our functions give use expected output. \n  \n  ```swift\npublic final class ArithmeticSequenceImplementationTests: XCTestCase {\n\n    // MARk: - Properties\n    public var naiveSum: NaiveSum!\n    public var gaussSum: GaussSum!\n\n    // MARK: - Life Cycle\n    public override func setUp() {\n        super.setUp()\n        naiveSum = NaiveSum()\n        gaussSum = GaussSum()\n    }\n\n    public override func tearDown() {\n        gaussSum = nil\n        naiveSum = nil\n        super.tearDown()\n    }\n\n    // Note: - I prefixed the tests with letters A,B,C... etc.. because Xcode run tests in alphabetic order by default,\n    // So prefixing them makes it easy to debug time complexity of each test.\n\n    // MARK: - Naive Tests\n    func test_A_NaiveApproachSumTo5GivesCorrectAnswer() {\n        // When\n        let sumToFithTerm = naiveSum.compute(\n            firstTerm: 1,\n            nthTerm: 5,\n            commonDifference: 2\n        )\n\n        // Then\n        XCTAssertEqual(sumToFithTerm, 25)\n    }\n\n    func test_B_NaiveApproachSumTo100GivesCorrectAnswer() {\n        // When\n        let sumToOneHundred = naiveSum.compute(\n            firstTerm: 1,\n            nthTerm: 100,\n            commonDifference: 1\n        )\n\n        // Then\n        XCTAssertEqual(sumToOneHundred, 5050)\n    }\n\n    func test_C_NaiveApproachSumTo_50000_GivesCorrectAnswer() {\n        // When\n        let sumToOneHundred = naiveSum.compute(\n            firstTerm: 10,\n            nthTerm: 50_000,\n            commonDifference: 15\n        )\n        // Then\n        XCTAssertEqual(sumToOneHundred, 18750125000)\n    }\n\n    // MARK: - Gauss Tests\n\n    func test_D_GaussAproachSumTo5GivesCorrectAnswer() {\n        // When\n        let sumToFithTerm = gaussSum.compute(\n            firstTerm: 1,\n            nthTerm: 5,\n            commonDifference: 2\n        )\n        // Then\n        XCTAssertEqual(sumToFithTerm, 25)\n    }\n\n    func test_E_GaussAproachSumTo100GivesCorrectAnswer()  {\n        // When\n        let sum = gaussSum.compute(\n            firstTerm: 1,\n            nthTerm: 100,\n            commonDifference: 1\n        )\n        // Then\n        XCTAssertEqual(sum, 5050)\n    }\n\n    func test_F_GaussAproachSumTo_50000_GivesCorrectAnswer() {\n        // When\n        let sumToOneHundred = gaussSum.compute(\n            firstTerm: 10,\n            nthTerm: 50_000,\n            commonDifference: 15\n        )\n\n        // Then\n        XCTAssertEqual(sumToOneHundred, 18750125000)\n    }\n\n}\n\n  ```\n  \n  ### Running Implemnentation Tests\n  In the sources folder there is a playground file named ArithmeticSequence. All tests are triggered in that file as follows. \n  ```swift\nimport Foundation\nimport XCTest\n  \nlet testObserver = TestObserver()\nXCTestObservationCenter.shared.addTestObserver(testObserver)\nArithmeticSequenceTests.defaultTestSuite.run()\n\n\n// MARK: - Sample Outputs\n/*\n\n Test Suite 'ArithmeticSequenceTests' started at 2022-04-03 01:45:51.791\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_A_NaiveApproachSumTo5GivesCorrectAnswer]' started.\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_A_NaiveApproachSumTo5GivesCorrectAnswer]' passed (0.049 seconds).\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_B_NaiveApproachSumTo100GivesCorrectAnswer]' started.\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_B_NaiveApproachSumTo100GivesCorrectAnswer]' passed (0.016 seconds).\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_C_NaiveApproachSumTo_50000_GivesCorrectAnswer]' started.\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_C_NaiveApproachSumTo_50000_GivesCorrectAnswer]' passed (0.031 seconds).\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_D_GaussAproachSumTo5GivesCorrectAnswer]' started.\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_D_GaussAproachSumTo5GivesCorrectAnswer]' passed (0.001 seconds).\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_E_GaussAproachSumTo100GivesCorrectAnswer]' started.\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_E_GaussAproachSumTo100GivesCorrectAnswer]' passed (0.001 seconds).\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_F_GaussAproachSumTo_50000_GivesCorrectAnswer]' started.\n Test Case '-[__lldb_expr_23.ArithmeticSequenceTests test_F_GaussAproachSumTo_50000_GivesCorrectAnswer]' passed (0.001 seconds).\n Test Suite 'ArithmeticSequenceTests' passed at 2022-04-03 01:45:51.907.\n      Executed 6 tests, with 0 failures (0 unexpected) in 0.099 (0.116) seconds\n */\n  ```\n  \n  \nInterpretations of the console output\n-  The ouput above is for the implementation details of our algorithms, All tests passed so we can rest assured that our algorithms will give us correct results for any data sets. \n- Note that the time stemps printed on console above, it is not safe to use them as a measure of performance because other tasks are being done by Xcode such as cleaning up the tests before running each test etc.. So  we are going to write better tests just for verifying the performance in the next section.\n\n\n\n### Performance Tests\nNow let's write tests specifically for measuring performance of individual functions regardless of the IDE background tasks. This will give us more correct results to verify our hypothesis. \n\n**Note:** Code snippet for this section too can be run using Swift Playgrounds.\nYou can find the source code [here.](ArithmeticSequence.playground)\n\n```swift\nimport Foundation\nimport XCTest\n\npublic final class ArithmeticSequenceSpeedMeasurementsTests: XCTestCase {\n\n    func test_A_NaiveSumSpeedForSmallDataSets() {\n        measureMetrics(\n            [.wallClockTime],\n            automaticallyStartMeasuring: false\n        ) {\n            startMeasuring()\n            let _ = computeSumOfNaturalNumbersUsingNaiveApproach(\n                firstTerm: 1,\n                nthTerm: 10,\n                commonDifference: 1\n            )\n\n            stopMeasuring()\n        }\n    }\n\n    func test_B_NaiveSumSpeedForLargeDataSets() {\n        measureMetrics(\n            [.wallClockTime],\n            automaticallyStartMeasuring: false\n        ) {\n            startMeasuring()\n            let _ = computeSumOfNaturalNumbersUsingNaiveApproach(\n                firstTerm: 1,\n                nthTerm: 100_000,\n                commonDifference: 1\n            )\n\n            stopMeasuring()\n        }\n    }\n\n    func test_C_GaussSpeedForSmallDataSets() {\n        measureMetrics(\n            [.wallClockTime],\n            automaticallyStartMeasuring: false\n        ) {\n            startMeasuring()\n            let _ = computeSumOfNaturalNumbersUsingGaussApproach(\n                firstTerm: 1,\n                nthTerm: 10,\n                commonDifference: 1\n            )\n\n            stopMeasuring()\n        }\n    }\n\n    func test_D_GaussSumSpeedForLargeDataSets() {\n        measureMetrics(\n            [.wallClockTime],\n            automaticallyStartMeasuring: false\n        ) {\n            startMeasuring()\n            let _ = computeSumOfNaturalNumbersUsingGaussApproach(\n                firstTerm: 1,\n                nthTerm: 100_000,\n                commonDifference: 1\n            )\n\n            stopMeasuring()\n        }\n    }\n\n}\n\n```\n\n ### Running Performance measurement Tests\n  Similar to implementation tests above tests for this section can also be triggered from the ArithmeticSequence playground included in Sources folder as follows.\n  ```swift\n  import Foundation\nimport XCTest\n  \nlet testObserver = TestObserver()\nXCTestObservationCenter.shared.addTestObserver(testObserver)\nArithmeticSequenceSpeedMeasurementsTests.defaultTestSuite.run()\n  \n// MARK: - Sample Output\n/*\n\n Test Suite 'ArithmeticSequenceSpeedMeasurementsTests' started at 2022-04-03 03:31:00.706\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_A_NaiveSumSpeedForSmallDataSets]' started.\n \u003cunknown\u003e:0: Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_A_NaiveSumSpeedForSmallDataSets]' measured [Time, seconds] average: 0.000, relative standard deviation: 154.337%, values: [0.000144, 0.000015, 0.000013, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012, 0.000012], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: \"\", baselineAverage: , polarity: prefers smaller, maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_A_NaiveSumSpeedForSmallDataSets]' passed (0.266 seconds).\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_B_NaiveSumSpeedForLargeDataSets]' started.\n \u003cunknown\u003e:0: Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_B_NaiveSumSpeedForLargeDataSets]' measured [Time, seconds] average: 0.053, relative standard deviation: 8.010%, values: [0.054845, 0.053265, 0.063672, 0.053840, 0.054468, 0.052207, 0.048998, 0.048461, 0.049184, 0.050229], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: \"\", baselineAverage: , polarity: prefers smaller, maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_B_NaiveSumSpeedForLargeDataSets]' passed (0.782 seconds).\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_C_GaussSpeedForSmallDataSets]' started.\n \u003cunknown\u003e:0: Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_C_GaussSpeedForSmallDataSets]' measured [Time, seconds] average: 0.000, relative standard deviation: 42.445%, values: [0.000002, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001, 0.000001], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: \"\", baselineAverage: , polarity: prefers smaller, maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_C_GaussSpeedForSmallDataSets]' passed (0.253 seconds).\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_D_GaussSumSpeedForLargeDataSets]' started.\n \u003cunknown\u003e:0: Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_D_GaussSumSpeedForLargeDataSets]' measured [Time, seconds] average: 0.000, relative standard deviation: 42.183%, values: [0.000004, 0.000002, 0.000002, 0.000001, 0.000001, 0.000001, 0.000001, 0.000002, 0.000001, 0.000001], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: \"\", baselineAverage: , polarity: prefers smaller, maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100\n Test Case '-[ArithmeticSequence_Sources.ArithmeticSequenceSpeedMeasurementsTests test_D_GaussSumSpeedForLargeDataSets]' passed (0.252 seconds).\n Test Suite 'ArithmeticSequenceSpeedMeasurementsTests' passed at 2022-04-03 03:31:02.273.\n      Executed 4 tests, with 0 failures (0 unexpected) in 1.552 (1.567) seconds\n */\n\n  ```\n\nDemistifying Console Outputs\n- Naive sum performance results.\n  - `test_A_NaiveSumSpeedForSmallDataSets` took 0.266 seconds. \n  - `test_B_NaiveSumSpeedForLargeDataSets` took 0.782 seconds (Almost 3 times the small data sets) -\u003e` O(n)` runtime.\n \n- Gauss Arithmetic sum performance results. \n  - `test_C_GaussSpeedForSmallDataSets` took 0.253 seconds.\n  - `test_D_GaussSumSpeedForLargeDataSets` Surprisingly  took 0.252 seconds which is the almost exactly similar ( `O(1)` run time) to the method for small data sets above.\n\n## Other useful formulas related to Arithmetic Progression\n- Sum of Natural Numbers (S\u003csub\u003en\u003c/sub\u003e) =\u003e n/2(n+1)\n- Sum of Square Series (S\u003csub\u003en\u003csup\u003e2\u003c/sup\u003e\u003c/sub\u003e) =\u003e  n/6(n+1)(2n+1)\n- Sum of Cubic Series (S\u003csub\u003en\u003csup\u003e3\u003c/sup\u003e\u003c/sub\u003e) =\u003e (n/2(n+1))\u003csup\u003e2\u003c/sup\u003e\n\n## Suggested Learning Materials\n\nIf you are new to Arithmetic Progression (AP) or you just need to review the concepts, I recommend the following materials. \n- [Reading - Nth Term of an AP](https://byjus.com/maths/nth-term-of-an-ap/#:~:text=Nth%20term%20of%20an%20AP%2C%20an%20%3D%20a,%2B(n%2D1)d.)\n- [Reading - Sum of N Terms of AP And Arithmetic Progression](https://byjus.com/maths/sum-of-n-terms/)\n- [Youtube - Arithmetic Sequences and Arithmetic Series - Basic Introduction](https://www.youtube.com/watch?v=XZJdyPkCxuE\u0026t=1016s\u0026ab_channel=TheOrganicChemistryTutor)\n- [Wikipedia - Arithmetic progression](https://en.wikipedia.org/wiki/Arithmetic_progression#:~:text=An%20alternate%20form%20results%20from%20re%2Dinserting%20the%20substitution%3A,%3A)\n- [Big-O Cheat Sheet](https://www.bigocheatsheet.com/)\n\n\n## What Next? \nThere is no a strict requirement to what to add next but I have the following planned for the near future. \nFeel free to contribute. \n- Add Python sample projects. \n- Add more real world examples. \n- Add other useful maths concepts with code samples. \n\n## Contributing\nThis is a work in progress so, I welcome any contributions which involves usage of maths theorem/formulas to achieve high performance algorithms. \nPlease see the [CONTRIBUTING](docs/CONTRIBUTING.md) for how to get involved.\n    \n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmussacharles%2Fmaths-for-fast-algorithms","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fmussacharles%2Fmaths-for-fast-algorithms","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fmussacharles%2Fmaths-for-fast-algorithms/lists"}