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

add code for goldbach conjecture algorithms #276

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
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
55 changes: 55 additions & 0 deletions maths/goldbach_conjecture.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import {
takeLeft,
} from 'fp-ts/lib/Array'

import { isPrime } from './primes'

function range(start: number, end: number, step: number = 1): number[] {
const result: number[] = [];
for (let i = start; i < end; i += step) {
result.push(i);
}
return result;
}

/**
* @function goldbachNumbers
* @description Return the goldbach numbers for a given even number
* @param {Number} n - a positive even number
* @return {Number} - an array of two numbers representing the goldbach numbers for N
* @see https://en.wikipedia.org/wiki/Goldbach%27s_conjecture
* @example goldbachNumbers(28) = [5, 23]
* @example goldbachNumbers(16) = [5, 11]
* @example goldbachNumbers(20) = [3, 17]
*/
export const goldbachNumbers = (n: number): number[] => {
const primes = range(2,n).filter( (m: number): Boolean => isPrime(m) && isPrime(n - m))
if (primes.length == 0) {
[]
}
let m = takeLeft(1)(primes)[0]
return [m, n-m]
}


/**
* @function goldbachCompositions
* @description Return the goldbach numbers for all even numbers in a given range of positive integers, low and high
* @param {Number, Number} low and high, low < high
* @return {Number} - an array of tuples with the first element representing the even number, and the second is the two primes that sum to it.
* @see https://en.wikipedia.org/wiki/Goldbach%27s_conjecture
* @example goldbachCompositiions(20, 30) = [
* [20,[3,17]],
* [22,[3,19]],
* [24,[5,19]],
* [26,[3,23]],
* [28,[3,25]]
* ]
*/
export const goldbachCompositions = (low: number, high: number): [number, number[]][] => {
let lo = (low % 2 == 0) ? low : low + 1
let hi = (high % 2 == 0) ? high : high - 1


return range(lo, hi, 2).map((n: number) => [n, goldbachNumbers(n)] )
}
14 changes: 14 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,8 @@
"prepare": "husky install"
},
"author": "TheAlgorithms",
"license": "MIT"
"license": "MIT",
"dependencies": {
"fp-ts": "^2.16.9"
}
}