Exemple #1
0
        public BigInt GetSumPrimes(int min, int max)
        {
            PrimeCalculator calculator = new PrimeCalculator();
            var primes = calculator.GetAllPrimes(max);
            BigInt sum = 0;
                foreach (var prime in primes)
                {

                    BigInt p = prime;
                    for (;;)
                    {

                        var l = checked ((max / p - (min - 1) / p) * prime);
                        if (l > 0)
                            sum += l;
                        else
                        {
                            break;

                        }
                        p *= prime;
                    }
                }
            return sum;
        }
Exemple #2
0
        static int Calculate(int n)
        {
            PrimeCalculator calculator = new PrimeCalculator();
            var primes = calculator.GetAllPrimes((int)Math.Sqrt(n));
            bool[] numbers = new bool[n+1];

            for (int i = 0; i < primes.Count; i++)
            {
                var pi = primes[i];
                var i4 = pi * pi * pi* pi;
                if (i4 > n)
                    break;

                for (int j = 0; j < primes.Count; j++)
                {
                    var pj = primes[j];
                    var j3 = pj * pj * pj;
                    if (i4+j3 > n)
                        break;

                    for (int k = 0; k < primes.Count; k++)
                    {
                        var pk = primes[k];
                        var k2 = pk*pk;
                        if (i4+j3+k2 > n)
                            break;

                        numbers[i4 + j3 + k2] = true;
                    }
                }
            }

            return numbers.Count(x => x);
        }
        public void PrimeCalculatorTestOne()
        {
            int firstPrime      = 2;
            int calculatedPrime = PrimeCalculator.CalculatePrime(1);

            Assert.AreEqual(firstPrime, calculatedPrime);
        }
Exemple #4
0
        public void FindPrimes_WhenMaxNumberIsLowerThanFirstPrime_ReturnsEmptyList(int lowerThanFirstPrimeNumber)
        {
            var calculator = new PrimeCalculator();
            var primes     = calculator.FindPrimes(lowerThanFirstPrimeNumber);

            Assert.Equal(primes, Enumerable.Empty <int>());
        }
        public void PrimeCalculatorTestTwo()
        {
            int thirdPrime      = 5;
            int calculatedPrime = PrimeCalculator.CalculatePrime(3);

            Assert.AreEqual(thirdPrime, calculatedPrime);
        }
Exemple #6
0
        public ActionResult Problem41(uint n)
        {
            if (n > 9)
            {
                n = 9;
            }

            // Set up prime calculator
            var cal = new PrimeCalculator();

            // Keep trying until we run out of digits.
            while (n > 0)
            {
                List <int> digits       = Enumerable.Range(1, (int)n).ToList();
                var        permutations = new Permutations <int>(digits);

                var allPrimes = permutations.Select(numList => numList.MakeNumber())
                                .Where(num => cal.IsPrimeAutoExpand(num)).ToList();

                // If there is at least 1 prime with n-digit, find the maximum amongst these primes and
                // that's the answer
                if (allPrimes.Count > 0)
                {
                    ulong max = allPrimes.Max();
                    return(ViewAnswer(41, "The maximum " + n + "-digit pandigital prime is", max));
                }

                // Otherwise, reduce number of digits and try again.
                --n;
            }

            return(ViewAnswer(41, "No n-digit pandigital prime found.", 0));
        }
Exemple #7
0
        static void Main(string[] args)
        {
            PrimeCalculator calc = new PrimeCalculator();
            calc.GetAllPrimes(10000);
            for (int n = 1000; n < 10000; n++)
            {
                int d1 = n % 10;
                int d2 = (n / 10) % 10;
                int d3 = (n / 100) % 10;
                int d4 = n / 1000;

                var permutations = Permutator.Permutate(new int[] {d1, d2, d3, d4}.ToList());
                var numbers = new List<int>();
                foreach (var perm in permutations)
                {
                    var num = perm[0] + perm[1] * 10 + perm[2] * 100 + perm[3] * 1000;
                    if (calc.IsPrime((ulong)num) && !numbers.Contains(num) && num>999 && num>=n)
                        numbers.Add(num);
                }
                numbers.Sort();

                for (int i = 1; i < numbers.Count-1; i++)
                {
                    for (int j = i+1; j < numbers.Count; j++)
                    {
                        if (numbers[j]-numbers[i]==numbers[i]-numbers[0])
                            Console.Write("{0}{1}{2}\n", numbers[0], numbers[i], numbers[j]);
                    }
                }
            }
        }
Exemple #8
0
        static void Main(string[] args)
        {
            ulong result = 0;
            ulong N = (ulong)1e6;
            PrimeCalculator calc = new PrimeCalculator();
            var primes = calc.GetAllPrimes_Atkin((ulong)N);
            foreach (var prime in primes)
            {
                if (prime < 5)
                    continue;

                ulong fact = 1;
                ulong sum = 0;
                for (ulong k = 2; k <= prime - 5; k++)
                    fact = (fact * k) % prime;
                sum = (sum+fact) % prime;
                fact = (fact * (prime - 4) % prime);
                sum = (sum + fact) % prime;
                fact = (fact * (prime - 3) % prime);
                sum = (sum + fact) % prime;
                fact = (fact * (prime - 2) % prime);
                sum = (sum + fact) % prime;
                fact = (fact * (prime - 1) % prime);
                sum = (sum + fact) % prime;

                result = checked(result + sum % prime);

            }

            Console.WriteLine(result);
        }
Exemple #9
0
 public double ResilenceFactorFast(ulong n)
 {
     PrimeCalculator calc = new PrimeCalculator();
     var factors = calc.Factor(n).Distinct().ToList();
     ulong count = (ulong)factors.Count;
     long cancelNum = (long)n-1;
     for (ulong i = 1; i < (ulong)Math.Pow(2,count); i++)
     {
         ulong tmp = i;
         int index = 0;
         ulong bitNum = 0;
         long mul = -1;
         while (tmp > 0)
         {
             if (tmp % 2 == 1)
                 mul *= -factors[index];
             tmp /= 2;
             index++;
         }
         long numDiv = (long)(n-1) / mul;
         cancelNum -= numDiv;
     }
     var factor = (double)cancelNum / (n - 1);
     return factor;
 }
Exemple #10
0
        public ActionResult Problem7(uint n)
        {
            var cal = new PrimeCalculator(n);

            cal.ExtendToLength(n);
            return(ViewAnswer(7, "The " + n + "-th prime number is", cal.LastPrime));
        }
Exemple #11
0
        /// <summary>
        /// Receives data, file or anything valid as PrimeUsbData
        /// </summary>
        /// <param name="calculator">Calculator instance, null to avoid controlling the device</param>
        /// <returns></returns>
        private static PrimeUsbData ReceiveData(PrimeCalculator calculator)
        {
            PrimeUsbData d             = null;
            var          keepReceiving = true;

            if (calculator != null)
            {
                calculator.DataReceived += calculator_DataReceived;
                calculator.StartReceiving();
            }

            do
            {
                if (ReceivedBytes.Count > 0)
                {
                    // Check for valid structure
                    if (d == null)
                    {
                        if (calculator != null)
                        {
                            Console.WriteLine("Receiving data...");
                        }
                        d = new PrimeUsbData(ReceivedBytes.Peek(), null);
                    }

                    if (d.IsValid)
                    {
                        ReceivedBytes.Dequeue();

                        while (ReceivedBytes.Count > 0)
                        {
                            var tmp = ReceivedBytes.Dequeue();
                            d.Chunks.Add(tmp.SubArray(1, tmp.Length - 1));
                        }

                        if (d.IsComplete)
                        {
                            if (calculator != null)
                            {
                                calculator.StopReceiving();
                                calculator.DataReceived -= calculator_DataReceived;

                                Console.WriteLine("... done.");
                            }
                            keepReceiving = false;
                        }
                    }
                    else
                    {
                        // Discard and try with next chunk
                        ReceivedBytes.Dequeue();
                        d = null;
                    }
                }

                Thread.Sleep(500);
            } while (keepReceiving);

            return(d);
        }
Exemple #12
0
        static BigInt Calculate(int n)
        {
            var calculator = new PrimeCalculator();
            var primes = calculator.GetAllPrimes(n / 2);
            var sqr = Math.Sqrt(n);

            int numLessSqr = 0;
            while (primes[numLessSqr] < sqr)
                numLessSqr++;

            BigInt sum = numLessSqr * (numLessSqr+1) / 2;

            for (int i = 0; i < numLessSqr; i++)
            {
                Console.WriteLine(i);
                int tmp = 0;

                for (int j = numLessSqr; j < primes.Count; j++)
                {
                    if (primes[i] * primes[j] < n)
                        tmp++;
                    else
                        break;
                }
                sum += tmp;
            }

            return sum;
        }
        private void InitializeGui()
        {
            var v = Assembly.GetExecutingAssembly().GetName().Version;

            Text = String.Format("{0} v{1} b{2}", Application.ProductName, v.ToString(2), v.Build);

            // Save
            openFilesDialogProgram.Filter = Resources.FilterInput;
            openFileDialogProgram.Filter  = Resources.FilterInput;
            saveFileDialogProgram.Filter  = Resources.FilterOutput;

            _userFilesFolder = Registry.GetValue(@"HKEY_CURRENT_USER\Software\Hewlett-Packard\HP Connectivity Kit", "WorkFolder", null) as string;
            connectivityKitUserFolderToolStripMenuItem.Enabled = _userFilesFolder != null && Directory.Exists(_userFilesFolder);

            _emulatorFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "HP_Prime");
            sendToEmulatorKitToolStripMenuItem.Enabled = IsWorkFolderAvailable;
            emulatorToolStripMenuItem.Enabled          = sendToEmulatorKitToolStripMenuItem.Enabled;
            exploreVirtualHPPrimeWorkingFolderToolStripMenuItem.Enabled = sendToEmulatorKitToolStripMenuItem.Enabled;

            _emulatorExeFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),
                                            @"Hewlett-Packard\HP Prime Virtual Calculator\HPPrime.exe");

            //UpdateDevices();
            _calculator               = new PrimeCalculator();
            _calculator.Connected    += usbCalculator_OnSpecifiedDeviceArrived;
            _calculator.Disconnected += usbCalculator_OnSpecifiedDeviceRemoved;
            _calculator.DataReceived += usbCalculator_OnDataReceived;
            _calculator.CheckForChanges();
        }
Exemple #14
0
        public void FindPrimes_WhenMaxNumberIsEqualToOrGreaterThanFirstPrime_ReturnsPrimeNumbers(int maxNaturalNumber, int[] expectedResult)
        {
            var calculator = new PrimeCalculator();
            var primes     = calculator.FindPrimes(maxNaturalNumber);

            Assert.Equal(primes, expectedResult);
        }
Exemple #15
0
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            PrimeCalculator calc = new PrimeCalculator();
            var allprimes = calc.GetAllPrimes_Atkin(100000000);
            List<ulong> primes = new List<ulong>();
            foreach (var prime in allprimes)
            {
                var tmp = prime;
                bool[] digits = new bool[10];
                bool notok = false;
                while (tmp > 0)
                {
                    var digit = tmp % 10;
                    if (digit == 0 || digits[digit])
                    {
                        notok = true;
                        break;
                    }
                    digits[digit] = true;
                    tmp /= 10;
                }
                if (!notok)
                    primes.Add(prime);
            }
            FindSetsRecursive(primes, new List<ulong>(), new bool[10], 0, 0);

            Console.WriteLine(result);
        }
Exemple #16
0
        public string Run()
        {
            var pe = new PrimeEnumerator();

            string result = "";
            var    pc     = new PrimeCalculator();

            var query = from p in pe.SkipWhile(p => p < 1000).TakeWhile(p => p < 10000)
                        let digits = DigitHelper.SplitDigits(p).ToList()
                                     let permutations = new Permutations <int>(digits)
                                                        let backToDigits =
                from perm in permutations
                let digit = (int)DigitHelper.ConvertToNumber(perm)
                            where digit != p && PrimeCalculator.IsPrime(digit) //pc.IsPrimeCached(digit) //
                            select digit
                            select new { p, Permutations = backToDigits };

            var permutationsGreaterThanP = from pair in query
                                           let perms = from perm in pair.Permutations where perm > pair.p select perm
                                                       where perms.Any()
                                                       select new { pair.p, perms };

            var outputs = from pair in permutationsGreaterThanP
                          from perm in pair.perms
                          let k = perm + perm - pair.p
                                  where pair.perms.Contains(k)
                                  select String.Join("", pair.p, perm, k);

            return(outputs.ElementAt(_count));
        }
Exemple #17
0
        static ulong Calculate(ulong n)
        {
            PrimeCalculator calculator = new PrimeCalculator();
            var primes = calculator.GetAllPrimes_Atkin(n);
            ulong maxPrime = primes[primes.Count - 1];
            ulong sum = 0;

            for (int i = 0; i < primes.Count - 2; i++)
            {
                if (i%10000==0)
                    Console.WriteLine(i);

                var a = primes[i];
                var factors = (ulong)calculator.Factor(a + 1).Distinct().Prod();

                if (factors > 10)
                {
                    sum += CalculateByFactor(a, factors, maxPrime, primes);
                }
                else
                {
                    sum += CalculateByPrimes(i, primes, a, maxPrime);

                }
            }
            return sum;
        }
Exemple #18
0
    public static void Mainx()
    {
        // Fire off the calculation in a separate thread
        Task <int> task = new Task <int>(
            () => PrimeCalculator.FindPrimeN(200000));

        task.Start();

        // Display what the task is up to
        while (true)
        {
            TaskStatus status = task.Status;
            Console.WriteLine(status);
            if (task.IsCompleted)
            {
                break;
            }
            Thread.Sleep(1000);
        }

        // Blocks until task completes
        Console.WriteLine("Result: " + task.Result);

        // Verify that task completed
        System.Diagnostics.Trace.Assert(
            task.IsCompleted);

        Console.Read();
    }
Exemple #19
0
        static void Calculate(PrimeCalculator calculator, List<ulong> allPrimes, List<ulong> currentPrimes, int primeIndex, ulong currentMul, ulong limit)
        {
            if (currentMul > MinFound)
                return;

            var numSquareDivisors = (ulong)currentPrimes.GroupBy(x => x).Select(x => x.Count() * 2 + 1).Prod();
            var result = (numSquareDivisors + 1) / 2;
            if (result >= limit)
            {
                if (currentMul < MinFound)
                {
                    MinFound = currentMul;
                    Console.WriteLine("{0}  {1}", currentMul, result);
                }
                return;
            }

            var newPrimes = new List<ulong>(currentPrimes);
            newPrimes.Add(allPrimes[primeIndex]);
            Calculate(calculator, allPrimes, newPrimes, primeIndex, currentMul * allPrimes[primeIndex], limit);

            newPrimes = new List<ulong>(currentPrimes);
            newPrimes.Add(allPrimes[primeIndex+1]);
            Calculate(calculator, allPrimes, newPrimes, primeIndex+1, currentMul * allPrimes[primeIndex+1], limit);
        }
Exemple #20
0
        private void IsPrime(string input)
        {
            var number  = int.Parse(input);
            var isPrime = new PrimeCalculator().IsPrime(number);

            Console.WriteLine($"{number} is {(isPrime ? "" : "not ")}prime.");
        }
Exemple #21
0
        public ActionResult Problem35(ulong n)
        {
            var cal = new PrimeCalculator((uint)n / 3);

            cal.ExtendToMinimumGT(n);

            Func <ulong, bool> isCircular = (i) =>
            {
                ulong c         = i;
                uint  numDigits = Utils.NumOfDigits(c);
                ulong factor    = Utils.PowerOfTen(numDigits - 1);
                do
                {
                    ulong lower  = (c / 10);
                    ulong higher = (c % 10) * factor;   // Move rightmost digit to leftmost position
                    c = higher + lower;

                    if (!cal.IsPrimeInRange(c))
                    {
                        return(false);
                    }
                }while (c != i);

                return(true);
            };

            int cnt = cal.Primes.Count(isCircular);

            return(ViewAnswer(35, "The number of circular primes below " + n + " is", (uint)cnt));
        }
Exemple #22
0
        private static void RunParallelStuff(int start, int end)
        {
            Console.WriteLine("Sequential from {0} to {1}...", start, end);
            PrimeCalculator.MeassureTime(() => PrimeCalculator.GetPrimesSequential(start, end));

            Console.WriteLine("Parallel Partitioned from {0} to {1}...", start, end);
            PrimeCalculator.MeassureTime(() => PrimeCalculator.GetPrimesParallel(start, end));
        }
Exemple #23
0
        public ActionResult Problem10(ulong n)
        {
            var cal = new PrimeCalculator((uint)n / 3);

            cal.ExtendToMinimumGT(n);
            var sum = cal.Primes.Sum() - cal.LastPrime;

            return(ViewAnswer(10, "The sum of all primes below " + n + " is", sum));
        }
Exemple #24
0
 static void Main(string[] args)
 {
     PrimeCalculator calculator = new PrimeCalculator();
     ulong limit = 100000000;
     Stopwatch sw = Stopwatch.StartNew();
     var primes = calculator.GetAllPrimes_Atkin(limit / 2);
     Calculate(calculator, primes, new List<ulong>() {2}, 1, 2, limit );
     Console.WriteLine(sw.ElapsedMilliseconds/1000);
     Console.WriteLine(sum +1); // 1 is not calculated
 }
Exemple #25
0
        static void Main(string[] _)
        {
            Random random      = new();
            ulong  number      = (ulong)random.Next();
            var    primeResult = PrimeCalculator.GetPrimes(number);

            var a = SubmitPrimeNumber(new PrimeRecord(number, primeResult.IsPrime, primeResult.Primes)).Result;

            Console.WriteLine(a);
        }
Exemple #26
0
        static void CalculateRads(int n)
        {
            var primeCalculator = new PrimeCalculator();

            _rads = new int[n+1];
            _rads[1] = 1;
            for (int i = 2; i <= n; i++)
            {
                _rads[i] = primeCalculator.Factor(i).Distinct().Prod();
            }
        }
Exemple #27
0
        private async void UseParallel()
        {
            List <long> primes = null;

            await Task.Run(() =>
            {
                primes = PrimeCalculator.GetPrimesParallel(start, end);
            }).ConfigureAwait(false);

            Done(primes);
        }
        public void PrimeFactorsFromNumber40()
        {
            // arrange
            var number   = 40;
            var calc     = new PrimeCalculator();
            var expected = "2*2*2*5";
            // act
            var actual = calc.PrimeFactors(number);

            // assert
            Assert.Equal(expected, actual);
        }
        public void PrimeFactorsFromNumber1001()
        {
            // arrange
            var number = 1001;
            var calc   = new PrimeCalculator();

            // act
            Action act = () => calc.PrimeFactors(number);

            // assert
            Assert.Throws <ArgumentException>(act);
        }
        public void TheFirstPrimeIs2()
        {
            // Arrange
            var calculator = new PrimeCalculator(1);
            var log        = new CalculationLog();

            // Act
            calculator.Calculate(1, log);

            // Assert
            log.Items.Single().Result.Should().Be(2);
        }
Exemple #31
0
        public IEnumerator <int> GetEnumerator()
        {
            int x = 1;

            while (true)
            {
                x++;
                if (PrimeCalculator.IsPrime(x))
                {
                    yield return(x);
                }
            }
        }
Exemple #32
0
        static void Calculate(PrimeCalculator calculator, List<ulong> allPrimes, List<ulong> currentPrimes, int primeIndex, ulong currentMul, ulong limit)
        {
            if (Check(currentPrimes, calculator))
                sum += currentPrimes.Prod();

            for (int i = primeIndex; i < allPrimes.Count; i++)
            {
                if (currentMul * allPrimes[i] >= limit)
                    break;
                var newPrimes = new List<ulong>(currentPrimes);
                newPrimes.Add(allPrimes[i]);
                Calculate(calculator, allPrimes, newPrimes, i+1, currentMul*allPrimes[i], limit);
            }
        }
Exemple #33
0
        private static void WaitForDevice(PrimeCalculator calculator, int timeout)
        {
            Console.WriteLine("Connecting to the device..."); Console.WriteLine();
            var t = Stopwatch.StartNew();

            do
            {
                calculator.CheckForChanges();
                if (calculator.IsConnected)
                {
                    break;
                }
                Thread.Sleep(500);
            } while (t.Elapsed.TotalSeconds < timeout);
        }
Exemple #34
0
        public void Calculate(int divNum)
        {
            PrimeCalculator primeCalc = new PrimeCalculator();
            primes_ = primeCalc.GetFirstNPrimes(divNum);
            povers_ = new List<int>();
            nextMultiple_ = new SortedList<BigInt, int>();
            for (int i = 0; i < primes_.Count; i++)
            {
                povers_.Add(0);
                nextMultiple_.Add(primes_[i], i);
            }

            BigInt result = 1;

            Console.WriteLine("start");
            for (int i = 0; i < divNum; i++)
            {
                if (i%10000==0)
                    Console.WriteLine(i);
                var key = nextMultiple_.Keys[0];
                var minPrime = nextMultiple_[key];
                //result *= key;
                int pow = povers_[minPrime];
                povers_[minPrime] = (pow + 1) * 2 - 1;
                int nextPow = (povers_[minPrime] + 1) * 2 - 1;
                BigInt newValue = 1;
                for (int d = 0; d < nextPow - povers_[minPrime]; d++)
                    newValue *= primes_[minPrime];
                nextMultiple_.RemoveAt(0);
                nextMultiple_.Add(newValue, minPrime);
            }

            for (int i = 0; i < primes_.Count; i++)
            {
                if (i % 10000 == 0)
                    Console.WriteLine(i);

                BigInt primMul = 1;
                for (int j = 0; j < povers_[i]; j++)
                    primMul *= primes_[i];
                if (primMul > 1)
                {
                    result *= primMul;
                    result %= 500500507;
                }
            }
            Console.WriteLine(result % 500500507);
        }
Exemple #35
0
        public ActionResult Problem49(uint n)
        {
            var cal = new PrimeCalculator();

            cal.ExtendToMinimumGT(9999);    // We know that the prime numbers will be 4-digit, as stated in problem

            // Algorithm:
            // 1) Find all prime numbers between 1000 to 9999, group them by permutations
            // 2) Skip if number of permutations in group is < n
            // 3) Find the all arithmetic sequences within group with len >= n
            //    - Not all prime numbers with same permutation will be part of the arithemetic sequence, for example,
            //      for 1487 -> 4817 -> 8147, 1847 won't particpate.

            // Steps 1
            var prime_grps = from p in cal.Primes
                             where p >= 1000 && p <= 9999
                             group p by p.GetSortedDigits() into g
                             select g;

            // Step 2
            prime_grps = prime_grps.Where(g => g.Count() >= n);

            // Step 3
            var matched_series = prime_grps.SelectMany(g => Utils.FindArithemeticSeries(g, n));

            // Stringify solution.  Each member of series separates by a comma.  Series separates by semicolon
            var sb = new StringBuilder();

            foreach (var series in matched_series)
            {
                foreach (var member in series)
                {
                    sb.Append(member);
                    sb.Append(',');
                }
                if (sb.Length > 0)
                {
                    sb.Remove(sb.Length - 1, 1);                   // Remove last comma
                }
                sb.Append(";");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);                       // Remove last semicolon
            }
            return(ViewAnswer(49, "4-digit primes which are permutations of each other", sb.ToString()));
        }
Exemple #36
0
        static void Main(string[] args)
        {
            ulong MAX = (ulong)1e14;
            ulong result = 0;
            PrimeCalculator calc = new PrimeCalculator();
            calc.GetAllPrimes_Atkin((ulong)Math.Sqrt(MAX));

            Stack<ulong> candidates = new Stack<ulong>();

            for (ulong i = 1; i < 10; i++)
            {
                candidates.Push(i);
            }

            while (candidates.Count > 0)
            {
                var num = candidates.Pop();
                var sumDigits = SumDigits(num);
                if (num % sumDigits > 0)
                    continue;

                bool isStrong = calc.IsPrime(num / sumDigits);
                if (isStrong)
                {
                    for (ulong i = 0; i < 10; i++)
                    {
                        var tmp = AddDigit(num, i);
                        if (tmp>MAX)
                            break;
                        if (calc.IsPrime(tmp))
                            result += tmp;
                    }
                }
                for (ulong i = 0; i < 10; i++)
                {
                    var tmp = AddDigit(num, i);
                    if (tmp > MAX)
                        break;

                    candidates.Push(tmp);
                }

            }

            Console.WriteLine(result);
        }
Exemple #37
0
        static void Main(string[] args)
        {
            int maxCheck = 1000;
            SortedList<int, int>[] variants = new SortedList<int, int>[maxCheck];

            PrimeCalculator calculator = new PrimeCalculator();
            var primes = calculator.GetAllPrimes(maxCheck*2);

            variants[0] = variants[1] = new SortedList<int, int>();
            for (int i = 2; i < maxCheck; i++)
            {
                variants[i] = new SortedList<int, int>();
                int primeIndex = 0;
                int prime = 0;
                for(;;)
                {
                    prime = primes[primeIndex++];
                    if (prime > i)
                        break;
                    if (prime == i)
                        variants[i].Add(prime*prime*prime*prime*prime*prime, prime*prime*prime*prime*prime*prime);
                    else
                    {
                        foreach (var variant in variants[i-prime])
                        {
                            var value = variant.Key + prime * prime * prime *prime*prime*prime;
                            if (!variants[i].ContainsKey(value))
                                variants[i].Add(value, value);
                        }
                    }

                    if (variants[i].Count >= 5000)
                    {
                        for (int j=0; j<=i; j++)
                            Console.WriteLine(variants[j].Count);

                        Console.WriteLine(i);
                        return;
                    }

                }
            }

            //Console.WriteLine(variants[10].Count);
        }
Exemple #38
0
        static void Main(string[] args)
        {
            Calculate();
            return;

            PrimeCalculator calc = new PrimeCalculator();
            calc.GetAllPrimes_Atkin((ulong)5e8);

            ulong inc = 2 * 2 * 2*3 * 3 * 5 * 7 * 11 * 13 * 17 * 19;
            ulong n = inc;
            Console.WriteLine(inc);

            ulong max = 0;

            for (;;)
            {

                //for (ulong x = n+1; x <= 2*n ; x+=1)
                //{

                //    if ((n * x) % (x - n) == 0)
                //    {
                //        count++;
                //    }
                //}

                var count = (NumOfDivisorSquare(n, calc) + 1) / 2;
                if (count > max)
                {
                    Console.WriteLine("{0} {1}", n, count);
                    max = count;
                }
                if (count >= 4000000)
                {
                    Console.WriteLine(n);
                    return;
                }
                //Console.WriteLine(count);
                n+=inc;
            }
        }
Exemple #39
0
        public static int CalculateSmallestMultiple(int lowerBoundary, int upperBoundary)
        {
            List <int> primesInBoundary = PrimeCalculator.CalculatePrimesInSpan(lowerBoundary, upperBoundary + 1);

            int sqrtUpperBoundary = (int)Math.Sqrt(upperBoundary);
            int answer            = 1;

            foreach (int prime in primesInBoundary)
            {
                if (prime <= sqrtUpperBoundary)
                {
                    answer *= (int)Math.Pow(prime, (int)(Math.Log(upperBoundary) / Math.Log(prime)));
                }
                else
                {
                    answer *= prime;
                }
            }

            return(answer);
        }
Exemple #40
0
        static void Calculate()
        {
            PrimeCalculator calc = new PrimeCalculator();
            var primes = calc.GetAllPrimes_Atkin((ulong)100);

            ulong firstGuess = 1;
            ulong divNum = 1;
            int count = 0;
            while (divNum < N*2+1)
            {
                firstGuess *= primes[count];
                divNum *= 3;
                count ++;
            }

            MinFound = firstGuess;
            Console.WriteLine(firstGuess);
            Console.WriteLine(count);
            Calculate(calc, primes, new List<ulong>(){2}, 0, 2, N);
            //Console.WriteLine(MinFound);
        }
Exemple #41
0
        public ActionResult Problem27(uint n)
        {
            ulong max = 2 * n * n + n;  // because n^2 + n*n + n is divisible by n
            var   cal = new PrimeCalculator((uint)max / 3);

            int max_a = 0, max_b = 0, max_i = 0;
            int minus_n = (-1 * (int)n) + 1;

            for (int a = minus_n; a < n; a++)
            {
                for (int b = minus_n; b < n; b++)
                {
                    int i;
                    for (i = 0; i < n; i++)
                    {
                        long p = i * i + a * i + b;
                        if (p <= 0)
                        {
                            break;
                        }

                        if (!cal.IsPrimeAutoExpand((ulong)p))
                        {
                            break;
                        }
                    }

                    if (i > max_i)
                    {
                        max_i = i;
                        max_a = a;
                        max_b = b;
                    }
                }
            }

            string s = string.Format("a = {0} b = {1} n = 0..{2} a*b = ", max_a, max_b, max_i);

            return(ViewAnswer(27, s, max_a * max_b));
        }
Exemple #42
0
            private void Ready_Prime(IRuntime runtime, int myId, Message message)
            {
                // item 89
                int n = (int)message.Payload;

                // item 94
                Debug.WriteLine(n);
                // item 232
                var calculator = new PrimeCalculator();

                calculator.Client = myId;
                calculator.N      = n;


                Worker = runtime.AddDedicatedActor(
                    calculator
                    );
                // item 91
                Window.SwitchToWorking();
                // item 73
                CurrentState = StateNames.Calculating;
            }
Exemple #43
0
        private void Initialize(bool ignoreBaseKeys = false)
        {
            PublicKey = 0;

            Random rand = new Random();

            while (PublicKey == 0)
            {
                if (!ignoreBaseKeys)
                {
                    Prime     = PrimeCalculator.GenPseudoPrime(Bitlength, 10, rand);
                    Generator = PrimeCalculator.GenPseudoPrime(Bitlength, 10, rand);
                }

                byte[] bytes = new byte[Bitlength / 8];
                Randomizer.NextBytes(bytes);
                _privateKey = new BigInteger(bytes);

                if (_privateKey < 1)
                {
                    continue;
                }

                if (Generator > Prime)
                {
                    BigInteger temp = Prime;
                    Prime     = Generator;
                    Generator = temp;
                }

                PublicKey = BigInteger.ModPow(Generator, _privateKey, Prime);

                if (!ignoreBaseKeys)
                {
                    break;
                }
            }
        }
Exemple #44
0
        static void Main(string[] args)
        {
            var stopWatch = new Stopwatch();
            int number    = 900;
            var calc      = new PrimeCalculator();

            stopWatch.Start();
            var resultNumberString = calc.PrimeFactorsString(number);

            stopWatch.Stop();
            WriteLine($"{nameof(calc.PrimeFactorsString)} time stamp is " +
                      stopWatch.Elapsed +
                      " ms");
            stopWatch.Reset();
            stopWatch.Start();
            var resultNumberSB = calc.PrimeFactors(number);

            stopWatch.Stop();
            WriteLine($"{nameof(calc.PrimeFactors)} time stamp is " +
                      stopWatch.Elapsed +
                      " ms");
            WriteLine($"Result string is {resultNumberString}");
            WriteLine($"Result string builder is {resultNumberSB}");
        }
Exemple #45
0
        public ActionResult Problem47(uint n)
        {
            var   cal           = new PrimeCalculator();
            uint  cnt           = 0;
            ulong potentialLeft = 0;

            for (ulong i = 1; cnt < n; i++)
            {
                if (i.GetDistinctPrimeFactors(cal).Count() == n)
                {
                    if (cnt == 0)
                    {
                        potentialLeft = i;
                    }
                    ++cnt;
                }
                else
                {
                    cnt = 0;
                }
            }

            return(ViewAnswer(47, "Earliest consecutive integers with " + n + " prime factors starts at", potentialLeft));
        }
Exemple #46
0
        public static bool Check(List<ulong> primes, PrimeCalculator calculator)
        {
            int len = primes.Count;
            ulong len2 = checked((ulong)Math.Pow(2, len));

            for (ulong i = 0; i < len2; i++)
            {
                ulong mul1 = 1;
                ulong mul2 = 1;
                ulong tmp = i;
                for (int j = 0; j <= len/2; j++)
                {
                    if (tmp % 2 == 0)
                        mul1 *= primes[j];
                    else
                        mul2 *= primes[j];
                    tmp /= 2;
                }
                if (!calculator.IsPrime(mul1+mul2))
                    return false;
            }

            return true;
        }
Exemple #47
0
        public int Calculate(int n, int k)
        {
            PrimeCalculator calculator = new PrimeCalculator();
            var primes = calculator.GetAllPrimes(n);
            var primeCounts = new Dictionary<int, int>();
            for (int i=n-k+1; i<=n; i++)
            {
                if (i%10000==0)
                    Console.WriteLine(i);
                var factors = calculator.Factor(i);
                foreach (int factor in factors)
                {
                    if (primeCounts.ContainsKey(factor))
                        primeCounts[factor] = primeCounts[factor] + 1;
                    else
                    {
                        primeCounts.Add(factor, 1);
                    }
                }
            }
            for (int i = 2; i <= k; i++)
            {
                var factors = calculator.Factor(i);
                foreach (int factor in factors)
                {
                    primeCounts[factor] = primeCounts[factor] - 1;
                }
            }

            int sum = 0;
            foreach (var primeCount in primeCounts)
            {
                sum += primeCount.Key * primeCount.Value;
            }
            return sum;
        }
Exemple #48
0
        static BigInt Calculate(int n)
        {
            SortedList<int, int> foundPrimes = new SortedList<int, int>();
            SortedList<int, int> beingProcessed = new SortedList<int, int>();
            SortedList<int, int> processQueue = new SortedList<int, int>();
            PrimeCalculator calculator = new PrimeCalculator();
            var primes = calculator.GetAllPrimes(n);
            processQueue.Add(2,2);

            while (processQueue.Count > 0)
            {
                var number = processQueue.Keys[0];
                var maxNumber = processQueue.Values[0];

                processQueue.RemoveAt(0);

                foreach (var neighbour in GetNeighbours(number))
                {
                    if (neighbour > n)
                        continue;
                    if (neighbour == n)
                        continue;
                    if (foundPrimes.ContainsKey(neighbour))
                        continue;
                    if (primes.BinarySearch(neighbour) < 0)
                        continue;

                    if (processQueue.ContainsKey(neighbour))
                    {
                        if (processQueue[neighbour] < neighbour)
                            continue;
                    }
                    else
                        processQueue.Remove(neighbour);

                    if (neighbour > maxNumber)
                    {
                        foundPrimes.Add(neighbour, neighbour);
                        processQueue.Add(neighbour, Math.Max(maxNumber, neighbour));
                    }
                    else
                    {
                        int currentMax = int.MaxValue;
                        if (beingProcessed.ContainsKey(neighbour))
                        {
                            currentMax = beingProcessed[neighbour];
                        }
                        if (maxNumber < currentMax)
                        {
                            processQueue.Add(neighbour, Math.Max(maxNumber, neighbour));
                            beingProcessed[neighbour] = maxNumber;
                        }

                    }
                }
            }

            BigInt result = 0;
            foreach (var prime in primes)
            {
                result += prime;
            }

            foreach (var foundPrime in foundPrimes)
            {
                result -= foundPrime.Key;
            }
            return result-2;
        }
        public void IsNotPrimeTest()
        {
            int notPrime = 9;

            Assert.IsFalse(PrimeCalculator.IsPrime(notPrime));
        }
Exemple #50
0
            private void Ready_Prime(IRuntime runtime, int myId, Message message)
            {
                // item 89
                int n = (int)message.Payload;
                // item 94
                Debug.WriteLine(n);
                // item 232
                var calculator = new PrimeCalculator();
                calculator.Client = myId;
                calculator.N = n;

                Worker = runtime.AddDedicatedActor(
                calculator
                );
                // item 91
                Window.SwitchToWorking();
                // item 73
                CurrentState = StateNames.Calculating;
            }
Exemple #51
0
 static void Main(string[] args)
 {
     PrimeCalculator calculator = new PrimeCalculator();
     //Console.WriteLine(calculator.Factor(600851475143).Last().ToString());
     Console.WriteLine(calculator.Factor(600851475143).Last().ToString());
 }
Exemple #52
0
 static void Main(string[] args)
 {
     PrimeCalculator calc = new PrimeCalculator();
     Console.WriteLine(calc.GetAllPrimes_Atkin(2000000).Sum(x=>(decimal)x));
 }
        public void PrimeTimeTest()
        {
            int primeToCalculate = 10001;

            PrimeCalculator.CalculatePrime(primeToCalculate);
        }
Exemple #54
0
 static ulong NumOfDivisorSquare(ulong n, PrimeCalculator calc)
 {
     var primes = calc.Factor(n);
     return (ulong)primes.GroupBy(x => x).Select(x => x.Count()*2 + 1).Prod();
     //return Tuple.Create(primes.GroupBy(x => x).Select(x => x.Count() + 1).Prod(), primes.Count());
 }