Prime Number Utility : Math « Development Class « C# / C Sharp






Prime Number Utility

        
// Copyright 2008 Adrian Akison
// Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx
using System.Collections.Generic;
using System.Collections;

namespace CombinatorialCollections {
    /// <summary>
    /// Utility class that maintains a small table of prime numbers and provides
    /// simple implementations of Prime Factorization algorithms.  
    /// This is a quick and dirty utility class to support calculations of permutation
    /// sets with indexes under 2^31.
    /// The prime table contains all primes up to Sqrt(2^31) which are all of the primes
    /// requires to factorize any Int32 positive integer.
    /// </summary>
    public class SmallPrimeUtility {
        /// <summary>
        /// Utility class, no instances allowed.
        /// </summary>
        private SmallPrimeUtility() {
            ;
        }

        /// <summary>
        /// Performs a prime factorization of a given integer using the table of primes in PrimeTable.
        /// Since this will only factor Int32 sized integers, a simple list of factors is returned instead
        /// of the more scalable, but more difficult to consume, list of primes and associated exponents.
        /// </summary>
        /// <param name="i">The number to factorize, must be positive.</param>
        /// <returns>A simple list of factors.</returns>
        public static List<int> Factor(int i) {
            int primeIndex = 0;
            int prime = PrimeTable[primeIndex];
            List<int> factors = new List<int>();
            while(i > 1) {
                if(i % prime == 0) {
                    factors.Add(prime);
                    i /= prime;
                }
                else {
                    ++primeIndex;
                    prime = PrimeTable[primeIndex];
                }
            }
            return factors;
        }

        /// <summary>
        /// Given two integers expressed as a list of prime factors, multiplies these numbers
        /// together and returns an integer also expressed as a set of prime factors.
        /// This allows multiplication to overflow well beyond a Int64 if necessary.  
        /// </summary>
        /// <param name="lhs">Left Hand Side argument, expressed as list of prime factors.</param>
        /// <param name="rhs">Right Hand Side argument, expressed as list of prime factors.</param>
        /// <returns>Product, expressed as list of prime factors.</returns>
        public static List<int> MultiplyPrimeFactors(IList<int> lhs, IList<int> rhs) {
            List<int> product = new List<int>();
            foreach(int prime in lhs) {
                product.Add(prime);
            }
            foreach(int prime in rhs) {
                product.Add(prime);
            }
            product.Sort();
            return product;
        }

        /// <summary>
        /// Given two integers expressed as a list of prime factors, divides these numbers
        /// and returns an integer also expressed as a set of prime factors.
        /// If the result is not a integer, then the result is undefined.  That is, 11 / 5
        /// when divided by this function will not yield a correct result.
        /// As such, this function is ONLY useful for division with combinatorial results where 
        /// the result is known to be an integer AND the division occurs as the last operation(s).
        /// </summary>
        /// <param name="numerator">Numerator argument, expressed as list of prime factors.</param>
        /// <param name="denominator">Denominator argument, expressed as list of prime factors.</param>
        /// <returns>Resultant, expressed as list of prime factors.</returns>
        public static List<int> DividePrimeFactors(IList<int> numerator, IList<int> denominator) {
            List<int> product = new List<int>();
            foreach(int prime in numerator) {
                product.Add(prime);
            }
            foreach(int prime in denominator) {
                product.Remove(prime);
            }
            return product;
        }

        /// <summary>
        /// Given a list of prime factors returns the long representation.
        /// </summary>
        /// <param name="value">Integer, expressed as list of prime factors.</param>
        /// <returns>Standard long representation.</returns>
        public static long EvaluatePrimeFactors(IList<int> value) {
            long accumulator = 1;
            foreach(int prime in value) {
                accumulator *= prime;
            }
            return accumulator;
        }

        /// <summary>
        /// Static initializer, set up prime table.
        /// </summary>
        static SmallPrimeUtility() {
            CalculatePrimes();
        }

        /// <summary>
        /// Calculate all primes up to Sqrt(2^32) = 2^16.  
        /// This table will be large enough for all factorizations for Int32's.
        /// Small tables are best built using the Sieve Of Eratosthenes,
        /// Reference: http://primes.utm.edu/glossary/page.php?sort=SieveOfEratosthenes
        /// </summary>
        private static void CalculatePrimes() {
            // Build Sieve Of Eratosthenes
            BitArray sieve = new BitArray(65536, true);
            for(int possiblePrime = 2; possiblePrime <= 256; ++possiblePrime) {
                if(sieve[possiblePrime] == true) {
                    // It is prime, so remove all future factors...
                    for(int nonPrime = 2 * possiblePrime; nonPrime < 65536; nonPrime += possiblePrime) {
                        sieve[nonPrime] = false;
                    }
                }
            }
            // Scan sieve for primes...
            myPrimes = new List<int>();
            for(int i = 2; i < 65536; ++i) {
                if(sieve[i] == true) {
                    myPrimes.Add(i);
                }
            }

        }

        /// <summary>
        /// A List of all primes from 2 to 2^16.
        /// </summary>
        public static IList<int> PrimeTable {
            get {
                return myPrimes;
            }
        }

        private static List<int> myPrimes = new List<int>();

    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Demonstrate Math.Sin(), Math.Cos(), and Math.Tan(). Demonstrate Math.Sin(), Math.Cos(), and Math.Tan().
2.Find the radius of a circle given its area. Find the radius of a circle given its area.
3.Math operators
4.Use Math.Round
5.Math.Sign
6.Math.Abs
7.Math.Min
8.Converts a degrees angle into a radians angle.
9.Converts a radians angle into a degrees angle.
10.Converts degrees to radians.
11.Gets the mean value from a list
12.Gets the median from the list
13.Gets the standard deviation
14.Statistical functions: Mean
15.Statistical functions: Standard Deviation
16.The Method converts the temperature in Fahrenheit to Celcius
17.The Method converts the temperature in Celcius to Fahrenheit
18.Returns the maximum value of three numbers
19.Returns the minimum value of three numbers
20.rounds val to the nearest fractional value
21.Combines two input numbers in some proportion.
22.Normalise Angle
23.wraps the mod result to avoid negative results.
24.Method that calculates the Greatest Common Divisor (GCD) of two positive integer numbers.
25.Calculates the floor of the log, base 2, of 'x'.
26.Calculates the Least Common Multiple (LCM) of two strictly positive integer numbers.
27.Get Prime, Is prime
28.Same as System.Math.Acos but if angle is out of range, the result is clamped.
29.Math.Abs returns the absolute value of a Decimal number.
30.Math.Acos
31.Math.Asin returns the angle whose sine is the specified number.
32.Math.Atan Returns the angle whose tangent is the specified number.
33.Math.Atan2 Returns the angle whose tangent is the quotient of two specified numbers.
34.Math.BigMul Produces the full product of two 32-bit numbers.
35.Math.Ceiling Returns the smallest integral value that is greater than or equal to the specified decimal number.
36.Math.Cos Returns the cosine of the specified angle.
37.Math.Cosh returns the hyperbolic cosine
38.Math.DivRem calculates the quotient of integers and returns the remainder in an output parameter.
39.Math.E Field Represents the natural logarithmic base, specified by the constant, e.
40.Math.Exp returns e raised to the specified power.
41.Math.Floor returns the largest integer less than or equal to the specified decimal number.
42.Math.IEEERemainder returns the remainder resulting from the division
43.Math.Log Method returns the natural (base e) logarithm of a specified number.
44.Math.Log Method returns the logarithm of a specified number in a specified base.
45.Math.Log10 Method returns the base 10 logarithm of a specified number.
46.Math.Max Method returns the larger of two 8-bit unsigned integers.
47.Math.Min Method returns the smaller of two 8-bit unsigned integers.
48.Math.PI Field represents the ratio of the circumference of a circle to its diameter,
49.Math.Pow Method returns a specified number raised to the specified power.
50.Math.Round Method rounds a decimal value to the nearest integral value.
51.Math.Sign Method returns a value indicating the sign of a decimal number.
52.Math.Sinh Method returns the hyperbolic sine of the specified angle.
53.Math.Sqrt Method returns the square root of a specified number.
54.Math.Tan Method returns the tangent of the specified angle.
55.Math.Tanh Method returns the hyperbolic tangent of the specified angle.
56.Math.Truncate calculates the integral part of a specified decimal number.
57.double extension method for Radian/Degree conversion
58.Fibonacci number
59.Almost equal and Epsilon
60.Is Value in the range
61.Angle Utility
62.Factorial value
63.Mean value
64.Get BMI
65.Conver Kg To Lb
66.Rational Class
67.Generic Max Min
68.Knuth shuffle
69.Calculate Distance between two points
70.Mesh Utilities
71.Generic Pair
72.Permutation demo
73.Calculate Variance
74.The normdist