/// <summary>生成随机的银行卡卡号 /// </summary> /// <param name="prefix"> </param> /// <param name="length"></param> /// <returns></returns> public static string GetFixNumberString(int prefix = 0, int length = 16) { if (length < 1) { throw new ArgumentException("卡号长度不能小于1"); } var prefixLength = UtilityMath.GetLength(prefix); var sb = new StringBuilder(length); if (prefix > 0) { if (prefixLength > length) { sb.Append(prefix.ToString().Substring(0, length)); } else { sb.Append(prefix); } } for (int i = 0; i < length - prefixLength; i++) { sb.Append(Random.Next(0, 9)); } return(sb.ToString()); }
public static Result LargeSum(Problem arguments) { string m; string sequence = arguments.Sequence; int digits = Convert.ToInt32(arguments.LongNumber); string[] numbers = sequence.Split(',').ToArray <string>(); int height = numbers.Length; int width = numbers[0].Length; int[,] matrix = UtilityMath.LoadMatrix(numbers, height, width); string sum = UtilityMath.AddMatrix(matrix); if (digits < sum.Length) { m = string.Format("The first {0} digits of the large sum are {1}.", digits, sum.Substring(0, digits)); } else { m = "Error: not enough digits specified."; } var r = new Result(arguments.Id, m); return(r); }
public PrimeSet(int c) { Count = c; Primes = UtilityMath.ErathostenesSieve(3, 20000); Minimums = Enumerable.Repeat(int.MaxValue, 5).ToArray(); Pairs = new HashSet <int> [Primes.Length]; Set = new int[Count]; var IsPrime = UtilityMath.IsPrimeUsingSquares.Memoize(); for (int a = 0; a < Primes.Length; a++) { Pairs[a] = new HashSet <int>(); int x = Primes[a]; for (int b = 0; b < Primes.Length; b++) { if (a == b) { continue; } int y = Primes[b]; if (IsPrime(UtilityMath.NumericConcat(x, y)) && IsPrime(UtilityMath.NumericConcat(y, x))) { Pairs[a].Add(y); } } } }
public static Result LargestProductInGrid(Problem arguments) { string sequence = arguments.Sequence; int adjacent = Convert.ToInt32(arguments.LongNumber); int maxProduct = int.MinValue, product = 0; CellList VisitedCellBlocks = new CellList(); //so we don't calculate on repeated blocks of adjcent cells //initialize grid from string sequence string[][] grid = sequence.Split(':').Select(row => row.Split(',')).ToArray(); int size = grid.Length; //get highest adajacent product of adjacents to every grid cell for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { product = UtilityMath.GetAdjacentMaxproduct(i, j, adjacent, size, grid, VisitedCellBlocks); if (product > maxProduct) { maxProduct = product; } } } var m = string.Format("The greatest product of {0} adjacent numbers in the same direction (up, down, left, right, or diagonally) in the {1}×{1} grid is {2}.", adjacent, size, maxProduct); var r = new Result(arguments.Id, m); return(r); }
/// <summary> /// https://projecteuler.net/problem=53 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result CombinatoricSelections(Problem arguments) { var limit = arguments.IntNumber; var count = 0; //todo: use factaorial in loop and cache it in array for (int n = 1; n <= 100; n++) { for (int r = 1; r < n; r++) { if (UtilityMath.BinomialCoefficients(n, r) >= limit) { count++; } } } var answer = count.ToString(); var message = string.Format("{0} not necessarily distinct, values of nCr, for 1 ≤ n ≤ 100, are greater than {1}.", answer, limit); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var result = new Result(arguments.Id, message) { Answer = answer }; return(result); }
public static Result LargestProductInSeries(Problem arguments) { string sequence = arguments.Sequence; int digits = Convert.ToInt32(arguments.LongNumber); string segment = string.Empty, digit = string.Empty; int start = 0; long product = long.MinValue; while (start + digits < sequence.Length) { segment = sequence.Substring(start, digits); start++; long p = UtilityMath.GetProduct(segment); if (p > product) { product = p; digit = segment; } } var m = string.Format("the adjacent digits [{0}] in the 1000-digit number that have the greatest product which is {1}.", string.Join("x", digit.ToArray()), product); var r = new Result(arguments.Id, m); return(r); }
/// <summary> /// https://projecteuler.net/problem=56 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result PowerfulDigitSum(Problem arguments) { var limit = arguments.IntNumber; long max = 100; // include all 100 * 1^b to begin with for (int a = 2; a < limit; a++) { for (int b = 1; b < limit; b++) { var ab = BigInteger.Pow(a, b); var sum = UtilityMath.DigitsSum(ab.ToString()); if (sum > max) { max = sum; } } } var answer = max.ToString(); var message = string.Format("The maximum digital sum of natural numbers of the form, a^b, where a, b < {0}, is {1}.", limit, answer); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var r = new Result(arguments.Id, message) { Answer = answer }; return(r); }
static Result LargestPrimeFactor(Problem arguments) { //n=600851475143;143;8462696833; long number = arguments.LongNumber; Tree <long> factors = new Tree <long>(); string m; UtilityMath.GetPrimeFactors(number, factors); bool isPrime = factors.Size == 0; long max = (long)factors.Max(); if (isPrime) { m = string.Format("The prime factors of {0} are [{1}], maximum is {2}", number, factors.ToString(), max); } else { m = string.Format("{0} is not a prime, but its prime factors are [{1}] with maximum {2}", number, factors.ToString(), max); } var r = new Result(arguments.Id, m); return(r); }
/// <summary> /// https://projecteuler.net/problem=61 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result CyclicalFigurateNumbers(Problem arguments) { var numbers = UtilityMath.GetPolygonalNumbers <int>(1009, 9999).ToArray(); var count = numbers.Length; var types = Enumerable.Range(0, count).ToArray <int>(); // array of polygonal number types used var setNumberOrder = UtilityString.GeneratePermutations <int>(types); // permutation of the types indicat1ing all combinations of these in a sequence of numbers var s = UtilityMath.GetNumericalCyclicalSet(setNumberOrder, numbers); var answer = s.set.Sum().ToString(); var message = string.Format("The sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set is {0}.", answer); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var r = new Result(arguments.Id, message) { Answer = answer }; return(r); }
/// <summary> /// https://projecteuler.net/problem=64 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result OddPeriodSquareRoots(Problem arguments) { var count = 0; var upperBound = arguments.IntNumber; for (int n = 2; n <= upperBound; n++) { if (UtilityMath.IsPerferctSquare(n)) { continue; } var p = UtilityMath.GetContinuedFractionExpansionPeriodicLengthForNonPerfectSquare(n); if (p % 2 == 1) //only if odd { count++; } } var answer = count.ToString(); var message = string.Format("The number of continued fractions for N ≤ {0} have an odd period is {1}.", upperBound, answer); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var r = new Result(arguments.Id, message) { Answer = answer }; return(r); }
/// <summary> /// https://projecteuler.net/problem=75 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result SingularIntegerRightTriangles(Problem arguments) { var perimeter = arguments.IntNumber; var values = 0; var a = UtilityMath.GetPythagoreanTriples_Pitagoras(120, false); for (int L = 12; L < perimeter; L++) { if (GetSingularPythagoreanTriples(L) == 1) { values++; } } var answer = values.ToString(); var message = string.Format("Given that L is the length of the wire, {0} values of L ≤ {1} can form exactly one integer sided right angle triangle.", answer, perimeter); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var r = new Result(arguments.Id, message) { Answer = answer }; return(r); }
static void Problem5(ProblemArguments arguments) { long maximum = arguments.Number; int[] multiples = new int[maximum]; bool found = false; long number = 0; for (int i = 1; i <= maximum; i++) { multiples[i - 1] = i; } while (!found && number < long.MaxValue) { if (!found) { number += maximum; } found = UtilityMath.IsMultiple(multiples, number); } if (found) { Console.WriteLine("{0} is the smallest positive number that is evenly divisible by {1}", number, string.Join(",", multiples)); } else { Console.WriteLine("No evenly positive multiple number found."); } }
static void Problem4_1(ProblemArguments arguments) { long number = 993 * 913; if (UtilityMath.IsPalindrome(number)) { Console.WriteLine("x. {0} is palipndrome", number); } }
//Override public void updateAIPosition() { //get delta x and y for rotating coordinates Point position = target.getAbsolutePositionOf(UtilityMath.dividePoint(this.targetPosition, zoomFactor)); MovingCamera.this.setDX((position.x - MovingCamera.this.getX()) / 30.0); MovingCamera.this.setDY((position.y - MovingCamera.this.getY()) / 30.0); getAngularComposite().setAngleInRadians(-target.getAngularComposite().getAngleInRadians()); //zoomFactor = zoom; }
public static Result PowerDigitSum(Problem arguments) { var e = Convert.ToInt16(arguments.LongNumber); var b = arguments.IntNumber; var p = UtilityMath.PowOverflow(b, e); var s = UtilityMath.DigitsSum(p); var m = string.Format("Sum of digits of {0}^{1} is {2}.", b, e, s); var r = new Result(arguments.Id, m); return(r); }
public static void Main(string[] args) { //UtilityHelper.Measure(() => SimpleForeach(), true, "Foreach loop:"); //UtilityHelper.Measure(() => ParallelForeach(2), true, "Parallel Foreach loop:"); UtilityHelper.Measure(() => { var f = UtilityMath.GetFactors(12000).ToArray(); Array.Sort(f); f[0] = 1; }, true, "Factor:"); UtilityHelper.Measure(() => ProductSumNumbers(12000), true, "ProductSumNumbers answer:"); }
private HashSet <int> MakePairs(int a) { HashSet <int> pairs = new HashSet <int>(); for (int b = a + 1; b < Primes.Length; b++) { if (UtilityMath.IsPrimeUsingSquares(UtilityMath.NumericConcat(Primes[a], Primes[b])) && UtilityMath.IsPrimeUsingSquares(UtilityMath.NumericConcat(Primes[b], Primes[a]))) { pairs.Add(Primes[b]); } } return(pairs); }
public static void Problem10(ProblemArguments arguments) { long sum = 0, limit = arguments.Number; for (long i = 2; i <= limit; i++) { if (UtilityMath.IsPrime(i)) { sum += i; } } Console.WriteLine("The sum of all the primes below {0} is {1}.", limit, sum); }
/// <summary> /// https://projecteuler.net/problem=59 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result XorDecryption(Problem arguments) { const char FirstChar = 'a'; const char LastChar = 'z'; var sum = 0; var key = string.Empty; var text = string.Empty; var cvsinfo = arguments.Sequence.Split('|'); var fileName = cvsinfo[0]; var delimiter = Convert.ToChar(cvsinfo[1]); var qualifier = Convert.ToChar(cvsinfo[2]); var cyphers = UtilityFile.ReadCsvToArray(fileName, delimiter, qualifier); var ascii = cyphers.Select(X => Convert.ToInt32(X)).ToArray(); var allPossiblePasswords = (from a in FirstChar.To(LastChar) from b in FirstChar.To(LastChar) from c in FirstChar.To(LastChar) select new[] { Convert.ToInt32(a), Convert.ToInt32(b), Convert.ToInt32(c) }).ToArray(); foreach (var password in allPossiblePasswords) { var decrypted = UtilityMath.Encrypt(ascii, password); text = new string(decrypted.Select(x => Convert.ToChar(x)).ToArray()); if (text.Contains(" the ")) //perform simple check: if Text contains single word 'the' it is in english { key = new string(password.Select(x => Convert.ToChar(x)).ToArray()); break; } } sum = text.Aggregate(0, (runningTotal, next) => runningTotal += next); var answer = sum.ToString(); var message = string.Format("The sum of the ASCII values in the original English text is {0}.", answer); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var r = new Result(arguments.Id, message) { Answer = answer }; return(r); }
public static Result NumbersToLetters(Problem arguments) { long sum = 0; long lower = arguments.Numbers[0]; long upper = arguments.Numbers[1]; for (long number = lower; number <= upper; number++) { sum += LengthWordRepresentation(UtilityMath.NumberToLetters(number)); } var m = string.Format("The number of letters used if all the numbers from {0} to {1} inclusive were written out in words is {2}.", lower, upper, sum); var r = new Result(arguments.Id, m); return(r); }
/// <summary> /// For right triangles, using Euclid formula, modified function for problem75 /// </summary> /// <param name="p">Triangle perimeter</param> /// <returns></returns> private static int GetSingularPythagoreanTriples(long p) { var count = 0; var bound = (long)Math.Sqrt(p / 2); long m; for (m = 2; m <= bound; m++) { if ((p / 2) % m == 0) { // m found long k; if (m % 2 == 0) { // ensure that we find an odd number for k k = m + 1; } else { k = m + 2; } while (k < 2 * m && k <= p / (2 * m)) { if (p / (2 * m) % k == 0 && UtilityMath.EuclidianGCD(k, m) == 1) { long d = p / 2 / (k * m); long n = k - m; long a = d * (m * m - n * n); long b = 2 * d * n * m; long c = d * (m * m + n * n); if (a + b + c == p) { count++; } // only consider those which only have one combination if (count > 1) { return(0); } } k += 2; } } } return(count); }
public static void Problem12(ProblemArguments arguments) { long count = arguments.Number; long number = (long)Math.Pow((double)count, 2); long number_of_divisors = 0; do { number++; if (UtilityMath.IsTriangularNumber(number)) { number_of_divisors = 0;// UtilityMath.NumberOfDivisor(number); } } while (number_of_divisors < count); Console.WriteLine("The value of the first triangle number to have over {0} divisors is {1}.", count, number); }
static Result LargestPalindromeProduct(Problem arguments) { long digits = arguments.LongNumber; long limit = (long)Math.Pow(10, digits) - 1; long number = 0; long i, j, pi = 0, pj = 0; bool found = false; long palindrome = UtilityMath.GenericLimit <long> .MinValue; string m; i = limit; j = limit; while (i > Math.Pow(10, digits - 1)) { j = limit; while (!found && j > Math.Pow(10, digits - 1)) { number = i * j; found = UtilityMath.IsPalindrome(number); j--; } i--; if (found && number > palindrome) { pi = i + 1; pj = j + 1; palindrome = number; found = false; } } if (palindrome == UtilityMath.GenericLimit <long> .MinValue && i == Math.Pow(10, digits - 1) && j == Math.Pow(10, digits - 1)) { m = string.Format("No palindrome found"); } else { m = string.Format("The largest palindrome made from the product of two 3-digit numbers is {0} = {1} x {2}", palindrome, pi, pj); } var r = new Result(arguments.Id, m); return(r); }
public static Result SummationOfPrimes(Problem arguments) { long sum = 0, limit = arguments.LongNumber; for (long i = 2; i <= limit; i++) { if (UtilityMath.IsPrime(i)) { sum += i; } } var m = string.Format("the sum of all the primes below {0} is {1}.", limit, sum); var r = new Result(arguments.Id, m); return(r); }
/// <summary> /// https://projecteuler.net/problem=68 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result Magic5GonRing(Problem arguments) { var n = arguments.ListOfNumbers; var ringSize = arguments.IntNumber; var sideLength = 3; var ring = UtilityMath.GetPentagonalRing(n, sideLength, ringSize); // traverse ring in circular index from smaller outer node // if iendex go: n, 0, 1,..., n-2, n-1 var index = new int[ringSize]; var v = 0; index[0] = ringSize - 1; for (var i = 1; i < ringSize; i++) { index[i] = v; v++; } var builder = new StringBuilder(); foreach (var i in index) { var side = ring[i]; foreach (var d in side) { builder.Append(d.ToString()); } } string answer = builder.ToString(); var message = string.Format("The maximum 16-digit string for a \"magic\" 5-gon ring is {0}.", answer); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var r = new Result(arguments.Id, message) { Answer = answer }; return(r); }
public static Result LatticePaths(Problem arguments) { ulong gridSize = arguments.BigNumber; var x = UtilityMath.FactorialOverFlow(gridSize); var y = UtilityMath.FactorialOverFlow(2 * gridSize); BigInteger a = BigInteger.Parse(x); BigInteger b = BigInteger.Parse(y); BigInteger n = BigInteger.Pow(a, 2); BigInteger routes = BigInteger.Divide(b, n); var m = string.Format("There are {0} route(s) in a {1}x{1} grid.", routes, gridSize); var r = new Result(arguments.Id, m); return(r); }
/// <summary> /// https://projecteuler.net/problem=58 /// </summary> /// <param name="arguments"></param> /// <returns></returns> public static Result SpiralPrimes(Problem arguments) { bool IsPrime(int n) { return(n != 1 && (n != 3 || n % 3 == 0) && (n != 2 || n % 2 == 0) && UtilityMath.IsPrimeUsingSquares(n)); } double ratio = 1; var step = 0; var length = 1; var corner = 1; var count = 0; while (ratio > 0.10) { length += 2; step += 2; for (int i = 1; i < 4; i++) // only check primality for three corners, so just skip the southwest corner numbers { corner += step; if (IsPrime(corner)) { count++; } } corner += step; ratio = (double)count / (2 * length - 1); } var answer = length.ToString(); var message = string.Format("The side length of the square spiral for which the ratio of primes along both diagonals first falls below {0}% is {1}.", ratio * 100, answer); if (Answers[arguments.Id] != answer) { message += string.Format(" => INCORRECT ({0})", Answers[arguments.Id]); } var r = new Result(arguments.Id, message) { Answer = answer }; return(r); }
static void Problem4(ProblemArguments arguments) { long digits = arguments.Number; long limit = (long)Math.Pow(10, digits) - 1; long number = 0; long i, j, pi = 0, pj = 0; bool found = false; long palindrome = UtilityMath.GenericLimit <long> .MinValue; i = limit; j = limit; while (i > Math.Pow(10, digits - 1)) { j = limit; while (!found && j > Math.Pow(10, digits - 1)) { number = i * j; found = UtilityMath.IsPalindrome(number); j--; } i--; if (found && number > palindrome) { pi = i + 1; pj = j + 1; palindrome = number; found = false; } } if (palindrome == UtilityMath.GenericLimit <long> .MinValue && i == Math.Pow(10, digits - 1) && j == Math.Pow(10, digits - 1)) { Console.WriteLine("No palindrome found"); } else { Console.WriteLine("The largest palindrome made from the product of two 3-digit numbers is {0} = {1} x {2}", palindrome, pi, pj); } //int digit = sequence[1]-48; //convert character to it's integer representation }
public Shape getGraphicRelativeRotationalBounds(double graphicsSizeFactorX, double graphicsSizeFactorY, double angleRadians, int areaExtender) { Rectangle box = new Rectangle(); int scaledWidth = (int)(this.getImage().getWidth(null) * graphicsSizeFactorX * this.getSizeFactor()); int sclaedHeight = (int)(this.getImage().getHeight(null) * graphicsSizeFactorY * this.getSizeFactor()); box.setSize( scaledWidth + areaExtender, sclaedHeight + areaExtender); box.setLocation( (int)((-areaExtender / 2 + this.getOffsetX()) * graphicsSizeFactorX * this.getSizeFactor()), (int)((-areaExtender / 2 + this.getOffsetY()) * graphicsSizeFactorY * this.getSizeFactor()) ); Point[] cornersArray = new Point[] { new Point((int)box.getMinX(), (int)box.getMinY()), new Point((int)box.getMaxX(), (int)box.getMinY()), new Point((int)box.getMaxX(), (int)box.getMaxY()), new Point((int)box.getMinX(), (int)box.getMaxY()) }; int[] newCornersX = new int[cornersArray.length]; int[] newCornersY = new int[cornersArray.length]; for (int i = 0; i < cornersArray.length; ++i) { Point rotatedCorner = UtilityMath.getRotationalAbsolutePositionOf(cornersArray[i], angleRadians); newCornersX[i] = rotatedCorner.x; newCornersY[i] = rotatedCorner.y; } Shape rotatedRectangle = new Polygon(newCornersX, newCornersY, newCornersX.length); box.setLocation( (int)((-areaExtender / 2 + this.getOffsetX()) * graphicsSizeFactorX * this.getSizeFactor()), (int)((-areaExtender / 2 + this.getOffsetY()) * graphicsSizeFactorY * this.getSizeFactor()) ); return(rotatedRectangle); }
public static Result DivisibleTriangularNumber(Problem arguments) { long count = arguments.LongNumber; long number = (long)Math.Pow((double)count, 2); long number_of_divisors = 0; do { number++; if (UtilityMath.IsTriangularNumber(number)) { number_of_divisors = 0;// UtilityMath.NumberOfDivisor(number); } } while (number_of_divisors < count); var m = string.Format("The value of the first triangle number to have over {0} divisors is {1}.", count, number); var r = new Result(arguments.Id, m); return(r); }