Data Analysis Mathematics Linear Algebra Statistics
New Version 8.1!

Supports .NET 6.0. Try it for free with our fully functional 60-day trial version. QuickStart Samples

# Prime Numbers QuickStart Sample (F#)

Illustrates working with prime numbers and the IntegerMath class in the Extreme.Mathematics namespace in F#.

```// Illustrates working with prime numbers using the
// IntegerMath class in the Extreme.Mathematics
// namespace of the Extreme Optimization Mathematics
// Library for .NET.

#light

open System

// We use many classes from the Extreme.Mathematics
// namespace.
open Extreme.Mathematics

//
// Factoring numbers
//

let printFactors n (factors : int[]) =
printf "%d = %d" n factors.
for index in 1..factors.Length-1 do
printf " * %d" factors.[index]
printfn ""

let printLongFactors (n : int64) (factors : int64[]) =
printf "%d = %d" n factors.
for index in 1..factors.Length-1 do
printf " * %d" factors.[index]
printfn ""

let n = 1001110110
let factors = IntegerMath.Factorize(n)
printFactors n factors

// Factors that occur multiple times is repeated as many times as necessary:
let n2 = 256 * 6157413
let factors2 = IntegerMath.Factorize(n)
printFactors n2 factors2

// The 64bit version can safely factor numbers up to 48 bits long:
let n3 = 1296523L * 1177157L
let factors3 = IntegerMath.Factorize(n3)
printLongFactors n3 factors3

//
// Prime numbers
//

// The IsPrime method verifies if a number is prime or not.
let p1 = 801853937
printfn "%d is prime? %b!" p1 (IntegerMath.IsPrime(p1))
let p2 = 801853939
printfn "%d is prime? %b!" p2 (IntegerMath.IsPrime(p2))

// MextPrime gets the first prime after a specified number.
// You can call it repeatedly to get successive primes.
// Let//s get the 10 smallest primes larger than one billion:
let mutable pn = 1000000000
printfn "\nFirst 10 primes greater than 1 billion:"
for index in 1..10 do
pn <- IntegerMath.NextPrime(pn)
printf "%16d" n
printfn ""

// PreviousPrime gets the last prime before a specified number.
pn <- 1000000000
printfn "Last 10 primes less than 1 billion:"
for index in 1..10 do
pn <- IntegerMath.PreviousPrime(pn)
printf "%16d" n
printfn ""

printf "Press Enter key to exit..."