public long GetSmallestReplacementPrimesWith(int startnumber, int maxNumber, int primevalfamily)
        {
            PrimeDictionary = Primes.GetPrimeFactorsBelowNumber(maxNumber).ToDictionary(e => e);
            minPrime        = startnumber;


            while (startnumber < maxNumber)
            {
                var str = startnumber.ToString();
                int max = 1 << str.Length;

                for (int hidingNumber = 1; hidingNumber < max; hidingNumber++)
                {
                    var    str2 = Star.Hide(str, hidingNumber);
                    long[] re   = GetReplacementPrimes(str2);

                    if (re.Length == primevalfamily)
                    {
                        return(re[0]);
                    }
                }

                startnumber++;
                while (startnumber % 2 == 0 || startnumber % 3 == 0)
                {
                    startnumber++;
                }
            }

            return(-1);
        }
 public E070TotientPermutation(int size)
 {
     primeFactors = Primes.GetPrimeFactorsBelowNumber((long)size);
     primeDict    = primeFactors.ToDictionary(e => e);
     vSize        = size;
     totient      = new Totient(size);
 }
Exemple #3
0
        public override long Solution()
        {
            long number = 0;

            const int  upperbound = 200000;
            List <int> primes     = Primes.EratosthenesSieve(upperbound);

            foreach (int nonPrime in ReversedEratosthenesSieve(upperbound))
            {
                if (number > 0)
                {
                    break;
                }

                if (nonPrime % 2 != 0)
                {
                    foreach (int prime in primes)
                    {
                        if (prime > nonPrime)
                        {
                            number = nonPrime;
                            break;
                        }

                        if (CanBeComposited(prime, nonPrime))
                        {
                            break;
                        }
                    }
                }
            }

            return(number);
        }
Exemple #4
0
    public void Lots()
    {
        int bound = 10101;

        int[] primes = Primes.GenerateArray(bound);

        foreach (int prime in primes)
        {
            Assert.IsTrue(IsPrime(prime), "is prime");
        }

        foreach (int prime in primes)
        {
            if (IsPrime(prime))
            {
                Assert.IsTrue(Contains(prime, primes),
                              "contains primes");
            }
            else
            {
                Assert.IsFalse(Contains(prime, primes),
                               "doesn't contain composites");
            }
        }
    }
Exemple #5
0
        public override object Run(RunModes runMode, object input, bool Logging)
        {
            Primes.InitPrimes();

            int i = 9;

            while (true)
            {
                bool foundOddComposite = false;
                if (Primes.IsPrime(i))
                {
                    i += 2; continue;
                }
                long sqrt = (long)Math.Sqrt(i);
                for (int j = 1; j < sqrt; j++)
                {
                    long diff = i - 2 * j * j;
                    if (Primes.IsPrime(diff))
                    {
                        foundOddComposite = true;
                        break;
                    }
                }
                if (!foundOddComposite)
                {
                    return(i);
                }
                i += 2;
            }
        }
Exemple #6
0
    static void Main()
    {
        Primes ob = new Primes();

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Next value is " + ob.GetNext());
        }

        Console.WriteLine("\nResetting");
        ob.Reset();

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Next value is " + ob.GetNext());
        }

        Console.WriteLine("\nStarting at 100");
        ob.SetStart(100);

        for (int i = 0; i < 5; i++)
        {
            Console.WriteLine("Next value is " + ob.GetNext());
        }
    }
Exemple #7
0
        public override object Run(RunModes runMode, object input, bool Logging)
        {
            int replacePrimeFamilyCount = (int)input;

            Primes.InitPrimes();
            Primes.TrimPrimes(9, 1000000);
            var primeList       = Primes.AllPrimes.OrderBy(p => p);
            int primeInitLength = 0;

            foreach (var start in primeList)
            {
                var stringStart       = start.ToString();
                var stringStartLength = stringStart.Length;
                if (stringStartLength > primeInitLength)
                {
                    Primes.InitPrimes((long)Math.Pow(10, stringStartLength));
                    Primes.TrimPrimes((long)(Math.Pow(10, stringStartLength - 1) - 1), (long)Math.Pow(10, stringStartLength));
                    primeInitLength = stringStartLength;
                }
                for (int indecesToReplace = 1; indecesToReplace < stringStartLength; indecesToReplace++)
                {
                    var indeces = Combinations.ChooseStringIndeces(indecesToReplace, stringStartLength);
                    foreach (var index in indeces)
                    {
                        var permutations = Permutations.GenerateReplacements(stringStart, index);
                        if (permutations.Count() >= replacePrimeFamilyCount && permutations.Count(Primes.IsPrime) >= replacePrimeFamilyCount)
                        {
                            return(permutations.Min());
                        }
                    }
                }
            }
            return(0);
        }
 public void PrimesLessThanXAreCorrect()
 {
     Primes.LessThan(8).Should().BeEquivalentTo(new[] { 2, 3, 5, 7 });
     Primes.LessThan(10).Should().BeEquivalentTo(new[] { 2, 3, 5, 7 });
     Primes.LessThan(12).Should().BeEquivalentTo(new[] { 2, 3, 5, 7, 11 });
     Primes.LessThan(100).Should().BeEquivalentTo(new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 });
 }
 public PrimeCollection(long size, int threads)
 {
     this.size = Math.Min((long)uint.MaxValue + 1, size);
     limit     = (int)Math.Ceiling(Math.Sqrt(size));
     block     = new bool[Math.Max(blockSizeSingleThreaded >> 1, limit)];
     primes    = new Primes();
     if (size <= 13)
     {
         // Special case for small collections because we handle
         // 2 and 3 differently.
         foreach (var prime in new uint[] { 2, 3, 5, 7, 11 })
         {
             if (size > prime)
             {
                 primes.AddPrime(prime);
             }
         }
     }
     else
     {
         GetDivisors(block);
         CreateCycle();
         GetPrimes(threads);
     }
 }
Exemple #10
0
        public override object Run(RunModes runMode, object input, bool Logging)
        {
            int runAndNumberDistinctPrimeFactors = (int)input;

            Primes.InitPrimes();

            int i        = 2;
            int startRun = 0;
            int runCount = 0;

            while (true)
            {
                if (Primes.UniquePrimeFactors(i, false).Count() == runAndNumberDistinctPrimeFactors)
                {
                    if (runCount == 0)
                    {
                        startRun = i;
                    }
                    runCount++;
                }
                else
                {
                    startRun = 0;
                    runCount = 0;
                }

                if (runCount == runAndNumberDistinctPrimeFactors)
                {
                    return(startRun);
                }
                i++;
            }
        }
Exemple #11
0
        public static int Solve()
        {
            int MAX          = 1000000;
            int TARGET_COUNT = 8;

            for (int digits = 1; digits <= 5; digits++)
            {
                GenerateCombinations(digits);
                //	PrintCombinations(digits);
            }

            _primes = new Primes(MAX);
            List <long> primesList = _primes.ToList();

            // start at prime > 10
            for (int i = 5; i < primesList.Count; i++)
            {
                long p = primesList[i];
                if (HasPrimesAfterSubstitutions(p, TARGET_COUNT))
                {
                    Console.WriteLine($"Found: {_primesFound[0]}");
                    break;
                }
            }

            return((int)_primesFound[0]);
        }
Exemple #12
0
        public void TestEnhancedMRProbablePrime()
        {
            int mrIterations = (PRIME_CERTAINTY + 1) / 2;

            for (int iterations = 0; iterations < ITERATIONS; ++iterations)
            {
                BigInteger      prime = RandomPrime();
                Primes.MROutput mr    = Primes.EnhancedMRProbablePrimeTest(prime, R, mrIterations);
                Assert.False(mr.IsProvablyComposite);
                Assert.False(mr.IsNotPrimePower);
                Assert.Null(mr.Factor);

                BigInteger primePower = prime;
                for (int i = 0; i <= (iterations % 8); ++i)
                {
                    primePower = primePower.Multiply(prime);
                }

                Primes.MROutput mr2 = Primes.EnhancedMRProbablePrimeTest(primePower, R, mrIterations);
                Assert.True(mr2.IsProvablyComposite);
                Assert.False(mr2.IsNotPrimePower);
                Assert.AreEqual(mr2.Factor, prime);

                BigInteger      nonPrimePower = RandomPrime().Multiply(prime);
                Primes.MROutput mr3           = Primes.EnhancedMRProbablePrimeTest(nonPrimePower, R, mrIterations);
                Assert.True(mr3.IsProvablyComposite);
                Assert.True(mr3.IsNotPrimePower);
                Assert.Null(mr.Factor);
            }
        }
Exemple #13
0
        public override long Solution()
        {
            int size = 1;

            double amountPrimes = 0;

            long   currentNumber = 1;
            double ratio;

            do
            {
                size++;
                for (int i = 0; i < 4; i++)
                {
                    currentNumber += size;
                    if (Primes.IsPrimeNumber(currentNumber))
                    {
                        amountPrimes++;
                    }
                }
                size++;

                double amountNumbers = size * 2 - 1;
                ratio = amountPrimes / amountNumbers;
            } while (ratio >= 0.10);

            return(size);
        }
Exemple #14
0
        static void Main()
        {
            Console.WriteLine("Hello TPL!");
            var sw = new Stopwatch();

            sw.Restart();

            var cts  = new CancellationTokenSource(5000);
            var task = Primes.FromRangeAsync(1, 200_000, cts.Token);

            try
            {
                var primes = task.Result;
                sw.Stop();
                var elapsed = sw.Elapsed;
                Console.WriteLine($"Found {primes.Count} primes after {elapsed}");
            }
            catch (Exception e)
            {
                // ! Exception property is null for cancelled task !
                Console.WriteLine($"Exception '{e}'.");
                Console.WriteLine($"Task exception '{task.Exception}'.");
                Console.WriteLine($"Task status {task.Status}.");
            }

            cts.Dispose();
        }
Exemple #15
0
        public long SmallestNumberDividedByAllNumbers(long UpToNumber)
        {
            long[] maxCountOfPrimNumber = new long[UpToNumber + 1];


            for (int i = 2; i <= UpToNumber; i++)
            {
                var group = Primes.GetPrimeFactorsInNumber(i).GroupBy(e => e);

                foreach (var g in group)
                {
                    if (maxCountOfPrimNumber[g.Key] < g.Count())
                    {
                        maxCountOfPrimNumber[g.Key] = g.Count();
                    }
                }
            }


            long smallestNumber = 1;

            for (int i = 2; i <= UpToNumber; i++)
            {
                for (int ii = 0; ii < maxCountOfPrimNumber[i]; ii++)
                {
                    smallestNumber *= i;
                }
            }

            return(smallestNumber);
        }
Exemple #16
0
    // Use Update to check if player is attempting to chomp
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            int    currentCorrectChomps = GameManager.Instance.currentNumberOfCorrectChomps;
            string currentTrigger       = ColliderScript.currentTrigger;

            for (int i = 0; i < GridContent.GRID_SIZE; i++)
            {
                int chompedNumber = int.Parse(GridManager.Instance.texts[i].text);

                string spaceName = GridManager.Instance.texts[i].name;
                if (currentTrigger == spaceName && Primes.Is(chompedNumber) && GridManager.Instance.texts[i].enabled)
                {
                    GridManager.Instance.texts[i].enabled = false;
                    GameManager.Instance.currentNumberOfCorrectChomps++;
                    GameManager.Instance.CorrectChomp();
                    break;
                }
                else if (currentTrigger == spaceName && !Primes.Is(chompedNumber))
                {
                    GridManager.Instance.texts[i].enabled = false;
                    GameManager.Instance.IncorrectChomp();
                    break;
                }
            }
        }
    }
Exemple #17
0
        public void primes_first_10_numbers()
        {
            var actual   = Primes.GeneratePrimes(10);
            var expected = Primes.WritePrimes(10);

            Assert.IsTrue(ElementsOnListsAreTheSame(actual, expected));
        }
Exemple #18
0
    public void ListPrime()
    {
        ArrayList centList = Primes.Generate(100);

        Assert.AreEqual(25, centList.Count);
        Assert.AreEqual(97, centList[24]);
    }
Exemple #19
0
        public void Run()
        {
            int  a = -999, b = -999;
            long testILongInt = 0;
            long maxConsecutivePrimes = 0, maxACoefficient = 0, maxBCoefficient = 0;

            for (int i = a; i <= 999; i++)
            {
                for (int j = b; j <= 999; j++)
                {
                    int n = 0, consecutivePrimes = 0;
                    while (true)
                    {
                        testILongInt = GetQuadratic(i, j, n++);
                        if (testILongInt > 0 && Primes.IsPrime(testILongInt))
                        {
                            consecutivePrimes++;
                        }
                        else
                        {
                            if (consecutivePrimes > maxConsecutivePrimes)
                            {
                                maxConsecutivePrimes = consecutivePrimes;
                                maxACoefficient      = i;
                                maxBCoefficient      = j;
                            }
                            break;
                        }
                    }
                }
            }

            this.result = (maxACoefficient * maxBCoefficient).ToString();
        }
Exemple #20
0
        public string Execute()
        {
            var primes = Primes.LoadPrimes(1000000);

            var primeSum = (long)0;

            primeLookup = new HashSet <long>(primes);

            var primesFound = 0;

            foreach (var p in primes)
            {
                if (p <= 7)
                {
                    continue;
                }

                if (TruncatablePrime(p))
                {
                    primeSum += p;
                    primesFound++;
                }
                if (primesFound == 11)
                {
                    break;
                }
            }
            return(primeSum.ToString());
        }
Exemple #21
0
    public void ListSingle()
    {
        ArrayList primes = Primes.Generate(2);

        Assert.AreEqual(1, primes.Count);
        Assert.IsTrue(primes.Contains(2));
    }
 protected bool isProbablePrime(BigInteger x)
 {
     /*
      * Primes class for FIPS 186-4 C.3 primality checking
      */
     return(!Primes.HasAnySmallFactors(x) && Primes.IsMRProbablePrime(x, param.Random, iterations));
 }
Exemple #23
0
        public string Execute()
        {
            primes = new HashSet <long>(Primes.GeneratePrimes(1, 20000));

            var highestYield = 0;
            var bestA        = 0;
            var bestB        = 0;


            var range = 1000;

            for (var a = -range; a < range; a++)
            {
                for (var b = -range; b <= range; b++)
                {
                    var total = CalculatePrimes(a, b);
                    if (total > highestYield)
                    {
                        bestA        = a;
                        bestB        = b;
                        highestYield = total;
                    }
                }
            }
            return((bestA * bestB).ToString());
        }
Exemple #24
0
        static void Main(string[] args)
        {
            var primesPow2 = Primes.GetPrimes((ulong)Math.Pow(uBound, 1 / 2D)).ToArray();
            var primesPow3 = Primes.GetPrimes((ulong)Math.Pow(uBound, 1 / 3D)).ToArray();
            var primesPow4 = Primes.GetPrimes((ulong)Math.Pow(uBound, 1 / 4D)).ToArray();
            var matching   = new HashSet <ulong>();

            for (int pow4idx = 0; pow4idx < primesPow4.Length; pow4idx++)
            {
                var pow4 = (ulong)Math.Pow(primesPow4[pow4idx], 4);
                for (int pow3idx = 0; pow3idx < primesPow3.Length; pow3idx++)
                {
                    var pow3 = (ulong)Math.Pow(primesPow3[pow3idx], 3);
                    if (pow4 + pow3 >= uBound)
                    {
                        break;
                    }
                    for (int pow2idx = 0; pow2idx < primesPow2.Length; pow2idx++)
                    {
                        var   pow2      = (ulong)Math.Pow(primesPow2[pow2idx], 2);
                        ulong candidate = pow2 + pow3 + pow4;
                        if (candidate > uBound)
                        {
                            break;
                        }
                        matching.Add(candidate);
                    }
                }
            }

            Console.WriteLine(matching.Count);
            Console.ReadLine();
        }
Exemple #25
0
    public static void Main()
    {
        int    limit;
        Primes obj  = new Primes();
        bool   stan = true;

        while (stan)
        {
            obj.Reset();
            Console.WriteLine("Aby wypisać liczby pierwsze, wpisz 1");
            Console.WriteLine("Aby zakończyć program, podaj liczbę 0");

            limit = Int32.Parse(Console.ReadLine());

            if (limit == 0)
            {
                stan = false;
                continue;
            }

            limit = 10000;

            PrimeCollection pc = new PrimeCollection(limit);
            Console.WriteLine("");
            foreach (int p in pc)
            {
                Console.WriteLine(p);
            }
        }
    }
Exemple #26
0
 public static void ThreadAndLambda()
 {
     using (Benchmark b = new Benchmark("Using threads via lambdas"))
     {
         Thread t1 = new Thread(() =>
         {
             Eratosthenes eratosthenes = new Eratosthenes();
             Console.WriteLine($"Task 1 starting {DateTime.Now.ToShortTimeString()}");
             Console.WriteLine(Primes.GetPrimeFactors(13187259, eratosthenes).PrettyPrint());
             Console.WriteLine($"Task 1 ending {DateTime.Now.ToShortTimeString()}");
         }
                                );
         Thread t2 = new Thread(() =>
         {
             Eratosthenes eratosthenes = new Eratosthenes();
             Console.WriteLine($"Task 2 starting {DateTime.Now.ToShortTimeString()}");
             Console.WriteLine(Primes.GetPrimeFactors(41724259, eratosthenes).PrettyPrint());
             Console.WriteLine($"Task 2 ending {DateTime.Now.ToShortTimeString()}");
         }
                                );
         t1.Start();
         t2.Start();
         t1.Join();
         t2.Join();
     }
 }
Exemple #27
0
        public void TestForExample()
        {
            const int number = 2143;

            Assert.IsTrue(Primes.IsPrimeNumber(number));
            Assert.IsTrue(Numbers.IsPandigital(number.ToString(), 4));
        }
Exemple #28
0
        public override long Solution()
        {
            long coefficientsProduct     = 0;
            int  amountConsecutiveValues = 0;

            for (int a = -1000; a <= 1000; a++)
            {
                for (int b = -1000; b <= 1000; b++)
                {
                    int  counter = 0;
                    long value;
                    do
                    {
                        value = GetValue(counter++, a, b);
                    }while(Primes.IsPrimeNumber(value));
                    counter--;

                    if (counter > amountConsecutiveValues)
                    {
                        amountConsecutiveValues = counter;
                        coefficientsProduct     = a * b;
                    }
                }
            }

            return(coefficientsProduct);
        }
Exemple #29
0
 private bool IsProbablePrime(BigInteger x, int iterations)
 {
     /*
      * Primes class for FIPS 186-4 C.3 primality checking
      */
     return(!Primes.HasAnySmallFactors(x) && Primes.IsMRProbablePrime(x, random, iterations));
 }
        public long GetFirstConsecutivenumberWith(int primefactors, int numberConsecutive)
        {
            primes = Primes.GetPrimeFactorsBelowNumber(200000).ToArray();
            long number = 1;

            while (true)
            {
                long distinctprimeFactorsInNumber = 0;
                for (int j = 0; j < numberConsecutive; j++)
                {
                    distinctprimeFactorsInNumber = GetDistinctprimeFactorsInNumber(number + j, primefactors);
                    if (distinctprimeFactorsInNumber != primefactors)
                    {
                        number += j;
                        break;
                    }
                }

                if (distinctprimeFactorsInNumber == primefactors)
                {
                    return(number);
                }

                number++;
            }
        }
        static void Main(string[] args)
        {
            Primes p = new Primes();
            long upperlimit = 600851475143;
            long testUpperLimit = (long)(Math.Round(Math.Sqrt(upperlimit)));
            long largestPrime = 0;

            for (long i = 0; i < testUpperLimit; i++)
            {
                if ((p.isPrime(i)) && (upperlimit % i == 0))
                    largestPrime = i;
            }
            Console.WriteLine(largestPrime);
            Console.ReadKey();
        }
        private void DoTheWork(Primes.Common.ICalculatePrimes calculator)
        {
            var sw = new Stopwatch();

            int max = Convert.ToInt32(bxHowMany.Text);
            int threadCount = Convert.ToInt32(bxThreads.Text);

            sw.Start();
            var p = new Primes.Common.Primes(calculator, threadCount);
            _primes = p.GetPrimes(2, max);
            sw.Stop();

            ShowPrimes();
            statusStrip1.Invoke(
                (MethodInvoker)
                    (() =>
                    {
                        statusStrip1.Items[0].Text = String.Format("Found {0:N0} primes in {1:N0} s.", _primes.Count,
                            sw.ElapsedMilliseconds / 1000);
                    }));
        }
Exemple #33
0
        static void Main(string[] args)
        {
            Console.Write("Prime Numbers Multiplication Table\n\n");

            Console.Write("Please enter a number greater than zero: ");

            var input = Console.ReadLine();

            try
            {
                var primeNumbers = new Primes().GetPrimes(input);
                var matrix = new MultiplicationTable().GetMatrix(primeNumbers);

                new Printer().ToConsole(matrix);
            }
            catch (ArgumentException)
            {
                Console.WriteLine("\n\nThe value entered is not valid, please run the app again.");
            }

            Console.Read();
        }
        public static void ShouldReturnArgumentException(this string input)
        {
            var primes = new Primes();

            Assert.Throws(typeof(ArgumentException), () => primes.GetPrimes(input));
        }
Exemple #35
0
        public long Run()
        {
            IEnumerable<long> primes = new Primes(long.MaxValue);

            return primes.ElementAt((int)m_primeNumber-1);
        }
        public static void ShouldReturnPrimeNumbers(this string input, int[] expected)
        {
            var primes = new Primes();

            Assert.Equal(expected, primes.GetPrimes(input));
        }
Exemple #37
0
 static void MyPrimes()
 {
     Primes p2to1000 = new Primes(2, 1000);
     foreach (long i in p2to1000)
     {
         Console.WriteLine("{0} ", i.ToString());
     }
 }
Exemple #38
0
    static void Main(string[] args)
    {
        Primes p = new Primes();

        using (StreamReader reader = File.OpenText(args[0]))
            while (!reader.EndOfStream)
            {
                string line = reader.ReadLine();
                if (line == null) continue;

                int[] range = line.Split(',').Select(x => int.Parse(x)).ToArray();
                Console.WriteLine(p.GetPrimeCount(range));
            }
    }