## Functions of Integers | Extreme Optimization Numerical Libraries for .NET Professional |

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 Factorize
method factorizes 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
2^{48} (roughly 3.10^{14}).
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:

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 π:

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);

Copyright © 2004-2021,
Extreme Optimization. All rights reserved.

*Extreme Optimization,* *Complexity made simple*, *M#*, and *M
Sharp* are trademarks of ExoAnalytics Inc.

*Microsoft*, *Visual C#, Visual Basic, Visual Studio*, *Visual
Studio.NET*, and the *Optimized for Visual Studio* logo

are
registered trademarks of Microsoft Corporation.