Functions of Integers

The IntegerMath class contains methods for functions on integers.

The IsOdd and IsEven methods return whether a number is odd or even, respectively. Overloads are available for all CLS compliant integer types, including Decimal.

The GreatestCommonDivisor method returns the greatest integer that divides both integer arguments. The LeastCommonMultiple method returns the smallest integer that is a multiple of both integer arguments.

The Factor method factors a non-zero positive integer into its prime factors. This method returns an integer array that contains the prime factors in ascending order. If the argument itself is prime, it returns an array with one element. The algorithm uses trial divides to factor out the small factors. It then switches to Pollard's Rho algorithm to find the remaining factors. The Rho algorithm breaks down for values greater than 248 (roughly 3.1014). Any factors greater than this value are returned unfactored.

Several functions can be used to generate prime numbers. The NextPrime method returns the smallest prime number greater than a value and PreviousPrime returns the largest value smaller than a value:

C#
var larger = IntegerMath.NextPrime(1000000000);
var smaller = IntegerMath.PreviousPrime(1000000000);

The Primes method enumerates successive prime numbers. This method has several overloads. Without arguments, the method simply lists all prime numbers up to MaxValue, which happens to be a prime number itself. An overload takes an integer which is an upper limit for the magnitude of the prime numbers in the sequence. The example below enumerates the prime numbers up to 10,000 and uses them to compute an approximation for π:

C#
double value = 1.0;
foreach (var p in IntegerMath.Primes(10000))
    value *= (1 + 1.0 / (p * p));
var pi = Math.Sqrt(15.0 / value);
Console.WriteLine("Pi            = {0}", Constants.Pi);
Console.WriteLine("Approximation = {0}", pi);