Coding challenges (for example the Euler project's problems) in C# I started to re-use code over problems and decided to put that stuff in this library.
Guidelines for the design of the library
Using Linq we can do
var isTrue = new int[] { 5, 20 }.Sum() == 25;
and with NumberUtil we can also do
var alsoTrue = new int[] { 5, 5 }.Product() == 25;
16.IsEven(); // returns true
16.IsOdd(); // returns false
17.IsEven(); // returns false
-17.IsOdd(); // return true
12345.NumberOfDigits(); // Returns 5
(-12345).NumberOfDigits(); // Also returns 5: sign not counted
BigInteger.Multiply(long.MaxValue, 1000).NumberOfDigits(); // Returns 22
BigInteger.Multiply(long.MaxValue, -1000).NumberOfDigits(); // Also returns 22
The parentheses are needed for the negative number or it would mean applying the unary operator -
on the result of 12345.NumberOfDigits()
.
var dig = 12345.Digits(); // Gets array with digits 1, 2, 3, 4 and 5 (dig[0] = 1 and dig[4] = 5)
var digits = 54321.Digits();
var value = digits.Number(); // value = 54321.
101.IsPrime(); // return true
99.IsPrime(); // return false
var factors = 30.PrimeFactors().ToArray(); // Array will contain 2, 3 and 5.
Primes are not iterated over in a sorted order.
Making a (Eratosthenes) sieve with the prime up to and including N of 211 (211 happens to be a prime)
var N = 211;
var primeNumbers = new PrimeNumbers(N); // the sieve
var numberOfPrimes = primeNumbers.Count; // will be 47 if N = 211
primeNumbers.IsPrime(101); // true
primeNumbers.IsPrime(210); // false
primeNumbers.IsPrime(211); // true
var largest = primeNumbers.Last(); // using LINQ to get the largest prime less or equal to N.
var fact1 = 5.Factorial(); // All componenets of tuple factorial (AsInt, AsLong and Value) assigned 5!
var fact2 = 13.Factorial(); // AsInt is 0 since 13! result do not fit an int, AsLong and Value is assigned 13!.
var fact3 = 50.Factorial(); // Only Value (BigInteger) assigned since 50! do not fit long.
Given a array with coefficients of a polynomial p p(x) can be evaluated:
var p = new int[] { 3, -2, 5 };
var y = p.Polynomial(5); // 3*5^2 - 2*5 + 5 = 70
Example of iterating over a number sequence, iterating over Fibonacci numbers
var fibSum = Sequences.Fibonacci.Take(6).Sum(); // Sums 0, 1, 1, 2, 3 and 5 : fibSum = 12
See the class Sequences for sequences implemented.
Finding sum of the five first perfect square numbers
var sqSum = ClosedForms.SumOfSquares(5); // sqSum = 55 = 1 + 4 + 9 + 16 + 25
Finding the 5th Fibonacci number
var fib = ClosedForms.NthFibonacci(5); // fib = 5
See the class ClosedForms for closed forms implemented.