public static void Main()
 {
     PrimeNumber p = new PrimeNumber();
     for(int i=0;i<1000;i++) {
         Console.Write(p.FindPrimeNumber(i));
         Console.Write(" ");
     }
     Console.WriteLine();
 }
Example #2
0
 static void Main(string[] args)
 {
     int Num;
         PrimeNumber FindPrimeNo = new PrimeNumber();
         string str;
         Console.WriteLine("Enter the number till which you want to show the prime Numbers");
         str = Console.ReadLine();
         Num = Convert.ToInt32(str);
         FindPrimeNo.PrimeNum(Num);
         Console.ReadLine();
 }
Example #3
0
        public void IsPrimeNumber_ZeroArg_Exception()
        {
            try
            {
                var prime = new PrimeNumber();

                //Zero is forbidden argument, so Exception must be thrown
                prime.IsPrimeNumber(0);

                Assert.Fail("ArgumentException expected");
            }
            catch (ArgumentException ex)
            {
                //Caller must know argument's name - so validate it here
                Assert.IsTrue(ex.ParamName == "number");
            }
        }
Example #4
0
        public int FindPrimeNumber(int i)
        {
            var found = false;

            if (i.Equals(1))
            {
                return(2);
            }
            if (i.Equals(2))
            {
                return(3);
            }
            if (i.Equals(3))
            {
                return(5);
            }

            int start    = 7;
            int position = 4;
            int result   = 0;

            while (!found)
            {
                long lastDigit = start % 10;
                if (!(lastDigit.Equals(1) || lastDigit.Equals(3) || lastDigit.Equals(7) || lastDigit.Equals(9)))
                {
                    start++;
                    continue;
                }

                if (position.Equals(i))
                {
                    found = true;
                }

                var p = new PrimeNumber(start);
                if (p.IsPrime())
                {
                    position++;
                    result = start;
                }
                start++;
            }
            return(result);
        }
Example #5
0
        /// <summary>
        /// Main Thread
        /// </summary>
        static void Main()
        {
            var listElements = (from r1 in Enumerable.Range(1, 10000)
                                select new
            {
                item = r1,
                sumDivisors = PrimeNumber.GetSumDivisors(Int64.Parse(r1.ToString()))
            }).ToList();

            var result = from r1 in listElements
                         from r2 in listElements
                         where r1.item != r2.item &&
                         r1.sumDivisors == r2.item &&
                         r1.item == r2.sumDivisors
                         select r1.item;

            Console.WriteLine("Solution: {0}", result.Sum());
        }
Example #6
0
        public void FactorizationTree_Add_AddSubNodes(long root, long sub1, long sub2)
        {
            // Arrange
            PrimeNumber     prime1          = new PrimeNumber(sub1);
            PrimeNumber     prime2          = new PrimeNumber(sub2);
            CompositeNumber compositeNumber = new CompositeNumber(root);

            FactorizationTree testTree = new FactorizationTree();

            // Act
            testTree.Add(compositeNumber);
            testTree.Add(prime1);
            testTree.Add(prime2);

            // Assert
            Assert.True(testTree.Count == 3);
            Assert.True(testTree.Root.value == root);
        }
Example #7
0
        static void DoPrimeNumber()
        {
            Console.Write("Calculate prime numbers until : ");
            int number = int.Parse(Console.ReadLine());

            PrimeNumber pn = new PrimeNumber();

            WarningMessage();
            var watch  = Stopwatch.StartNew();
            var result = pn.FindAllPrimesEratosthenes(number);

            watch.Stop();
            var elapsedMs = watch.ElapsedMilliseconds;

            Console.WriteLine($"\n Elapsed time : {elapsedMs} ms\n Number of occurences : {result.Count()}\n-------------------------------------------------\n ");
            Console.WriteLine("\nPress any key to continue...");
            Console.ReadKey();
        }
        private async Task <PrimeNumber> SaveNthPrimeNumberItem(PrimeNumber primeNumber)

        {
            PrimeNumber primeNumberItem = await GetNthPrimeNumberItem(primeNumber.Index);

            if (primeNumberItem == null)

            {
                primeNumber.PrimeValue = NthPrime.GetPrime(primeNumber.Index);

                _context.PrimeNumber.Add(primeNumber);

                await _context.SaveChangesAsync();

                return(primeNumber);
            }

            return(primeNumberItem);
        }
Example #9
0
        public static void SelectedOption(int option)
        {
            switch (option)
            {
            case 1:
                List <string> input = new List <string> {
                    "apple", "apple", "ball", "cup", "mango", "cup", "banana"
                };
                RemoveDuplicate.DistinctValues(input);
                break;

            case 2:
                PrimeNumber.PrimeNum();
                break;

            case 3:
                FizzBuzzChallenge.FizzBuzz();
                break;
            }
        }
Example #10
0
        /// <summary>
        /// Main Thread
        /// </summary>
        static void Main()
        {
            Int64      i        = 0;
            List <int> divisors = new List <int>();
            string     solution = String.Empty;

            while (divisors.Count < 500)
            {
                i++;

                TriangularNumber.AddNextTerm();

                solution = TriangularNumber.GetListTriangularNumber().Last();

                divisors = PrimeNumber.GetListDivisors(Int64.Parse(solution));
            }


            Console.WriteLine("Solution: {0}", solution);
        }
 public Sample <List <double> > NextSequence()
 {
     ++_sequenceCounter;
     for (int i = 0; i < _dimensionality; ++i)
     {
         var h = 0.0;
         var b = PrimeNumber.Get(i);
         var f = 1.0;
         var k = _sequenceCounter + _randomStart[i];
         while (k != 0)
         {
             f /= b;
             h += (k % b) * f;
             k /= b;
         }
         _sequence.Value[i]  = h + _randomShift[i];
         _sequence.Value[i] -= (long)_sequence.Value[i];
     }
     return(_sequence);
 }
Example #12
0
        public void IsPrimeNumberTest()
        {
            // Array of number that we know are prime
            var primeNumbers = new int[] { 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, 101, 103, 107, 109, 113, 127, 131, 137, 139,
                                           149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199 };

            foreach (var primeNumber in primeNumbers)
            {
                Assert.IsTrue(PrimeNumber.IsPrimeNumber(primeNumber));
            }

            // Array of non-prime numbers
            var nonPrimeNumbers = new int[] { 4, 8, 10, 12, 14, 16 };

            foreach (var nonPrimeNumber in nonPrimeNumbers)
            {
                Assert.IsFalse(PrimeNumber.IsPrimeNumber(nonPrimeNumber));
            }
        }
Example #13
0
 static string CheckPrimeNumber(string startNumber, string endNumber)
 {
     if (Regex.IsMatch(startNumber, @"^[0-9]+$") && Regex.IsMatch(endNumber, @"^[0-9]+$"))
     {
         PrimeNumber obj    = new PrimeNumber();
         List <int>  result = obj.generate(Convert.ToInt32(startNumber), Convert.ToInt32(endNumber));
         if (result.Count == 0)
         {
             return("No Prime Numbers");
         }
         else
         {
             return(string.Join(",", result));
         }
     }
     else
     {
         return("Invalid input");
     }
 }
Example #14
0
        static void Main(string[] args)
        {
            PrimeNumber primeNumber = new PrimeNumber();

            string[] numbers = FileSystem.F2().Split();

            int [] array = primeNumber.ToIntegerArray(numbers);

            List <int> primes = primeNumber.ToPrimeNumberArray(array);

            foreach (var i in primes)
            {
                Console.WriteLine(i);
            }

            primes.Sort();

            Console.WriteLine($"MIN PRIME NUMBER IS {primes[0]}");

            Console.ReadLine();
        }
Example #15
0
        /// <summary>
        /// Main Thread
        /// </summary>
        static void Main()
        {
            bool itemNotFound = true;

            for (int i = 1; itemNotFound; i++)
            {
                Dictionary <Int64, Int64> d1 = PrimeNumber.GetIntegerFactorization(i);
                Dictionary <Int64, Int64> d2 = PrimeNumber.GetIntegerFactorization(i + 1);
                Dictionary <Int64, Int64> d3 = PrimeNumber.GetIntegerFactorization(i + 2);
                Dictionary <Int64, Int64> d4 = PrimeNumber.GetIntegerFactorization(i + 3);

                bool distinctPrimes = CompareFactorizations(d1, d2) && CompareFactorizations(d1, d3) && CompareFactorizations(d1, d4) &&
                                      CompareFactorizations(d2, d3) && CompareFactorizations(d2, d4) &&
                                      CompareFactorizations(d3, d4);

                if (distinctPrimes)
                {
                    itemNotFound = false;
                    Console.WriteLine("Solution: {0}", i);
                }
            }
        }
Example #16
0
        static int primeCount(long n)
        {
            int     max = 0;
            decimal res = 1;

            for (long i = 1; i <= n; i++)
            {
                if (PrimeNumber.IsPrimeNumber(i))
                {
                    res = res * i;
                    if (res <= n)
                    {
                        max++;
                        arr.Add(i);
                    }
                    else
                    {
                        break;
                    }
                }
            }
            return(max);
        }
Example #17
0
        static void Main()
        {
            const int MAX_NUMBER = 50000000;

            PrimeNumber.CalculateTermsUntilValue((int)(Math.Sqrt(MAX_NUMBER) + 1));

            HashSet <double> solutions = new HashSet <double>();

            List <Int64> primes = PrimeNumber.GetListPrimes();

            for (int i = 0; i < primes.Count; i++)
            {
                double firstPow = Math.Pow(primes[i], 2);

                if (firstPow <= MAX_NUMBER)
                {
                    for (int j = 0; j < primes.Count; j++)
                    {
                        double secondPow = Math.Pow(primes[j], 3);

                        if (firstPow + secondPow <= MAX_NUMBER)
                        {
                            for (int k = 0; k < primes.Count; k++)
                            {
                                double result = firstPow + secondPow + Math.Pow(primes[k], 4);
                                if (result <= MAX_NUMBER)
                                {
                                    solutions.Add(result);
                                }
                            }
                        }
                    }
                }
            }

            Console.WriteLine("Solution: {0}", solutions.Count());
        }
Example #18
0
        public void PrimeFactoringTest()
        {
            var pr = new PrimeNumber((int)1e7);

            pr.PrimeFactoring(1 << 16).Should().Equal(new Dictionary <int, int>
            {
                { 2, 16 },
            });
            pr.PrimeFactoring(2 * 3 * 5).Should().Equal(new Dictionary <int, int>
            {
                { 2, 1 },
                { 3, 1 },
                { 5, 1 },
            });
            pr.PrimeFactoring(99991).Should().Equal(new Dictionary <int, int>
            {
                { 99991, 1 },
            });
            pr.PrimeFactoring(2147483647).Should().Equal(new Dictionary <int, int>
            {
                { 2147483647, 1 },
            });
            pr.PrimeFactoring(132147483703).Should().Equal(new Dictionary <long, int>
            {
                { 132147483703, 1 },
            });
            pr.PrimeFactoring(903906555552).Should().Equal(new Dictionary <long, int>
            {
                { 2, 5 },
                { 3, 8 },
                { 7, 1 },
                { 11, 2 },
                { 13, 1 },
                { 17, 1 },
                { 23, 1 },
            });
        }
Example #19
0
        internal static void Run()
        {
            List <long> primesList = new List <long>();

            for (int i = 0; i < 1000000; i++)
            {
                if (PrimeNumber.IsPrime(i))
                {
                    primesList.Add(i);
                }
            }


            long[] primes = primesList.ToArray();

            Stopwatch s = new Stopwatch();

            s.Start();

            int  number = 0;
            long value  = 0;

            int consec = 1;

            while (consec < primes.Length)
            {
                //Console.WriteLine(consec);

                for (int c = 0; c + consec < primes.Length; c++)
                {
                    long sum     = 0;
                    bool isBreak = false;
                    for (int i = 0; i < consec && c + i < primes.Length; i++)
                    {
                        sum += primes[c + i];

                        if (sum >= 1000000)
                        {
                            isBreak = true;
                            break;
                        }
                    }

                    if (isBreak || sum >= 1000000)
                    {
                        break;
                    }

                    if (primes.Contains(sum))
                    {
                        if (consec > number)
                        {
                            number = consec;
                            value  = sum;
                        }
                        break;
                    }
                }
                consec++;
            }

            //int number = 0;
            //long value = 0;

            //for (int i = 0; i < primes.Length; i++)
            //{
            //    Console.WriteLine(i);

            //    int numberOfPrimes = 0;
            //    long sum = 0;

            //    // number to iterate iterate primes
            //    for (int z = i; z < primes.Length; z++)
            //    {
            //        numberOfPrimes++;
            //        sum += primes[z];

            //        if (sum >= 1000000)
            //        {
            //            break;
            //        }

            //        if (primes.Contains(sum))
            //        {
            //            if (numberOfPrimes > number)
            //            {
            //                number = numberOfPrimes;
            //                value = sum;
            //            }
            //        }
            //    }
            //}

            s.Stop();

            double time = s.ElapsedMilliseconds / 1000.0d;

            Console.WriteLine("SOLUTION: (" + time + ") " + value);
        }
Example #20
0
 /// <summary>
 /// Main Thread
 /// </summary>
 static void Main()
 {
     Console.WriteLine("Solution: {0}", PrimeNumber.GetPrimeTerm(MAX_ITEM));
 }
Example #21
0
        /*
         * Get keys function, the function get as a parameter key length window. it done because we need to read the length from this form
         * */
        public void getKeys(KeyLengthWindow form)
        {
            // Generate two random numbers
            // Lets use our entropy based random generator
            Generator.Initialize(2);

            // For 1024 bit key length, we take 512 bits for first prime and 512 for second prime
            // Get same min and max
            BigInteger numMin = BigInteger.Pow(2, (form.BitLength / 2) - 1);
            BigInteger numMax = BigInteger.Pow(2, (form.BitLength / 2));

            // Create two prime numbers
            var p = new PrimeNumber();
            var q = new PrimeNumber();

            p.SetNumber(Generator.Random(numMin, numMin));
            q.SetNumber(Generator.Random(numMin, numMax));

            // Create threaded p and q searches
            pThread = new Thread(p.RabinMiller);
            qThread = new Thread(q.RabinMiller);

            // For timeout
            DateTime start = DateTime.Now;

            pThread.Start();
            qThread.Start();

            while (pThread.IsAlive || qThread.IsAlive)
            {
                TimeSpan ts = DateTime.Now - start;

                if (ts.TotalMilliseconds > (1000 * 60 * 5))
                {
                    try
                    {
                        pThread.Abort();
                    }
                    // ReSharper disable EmptyGeneralCatchClause
                    catch (Exception)
                    // ReSharper restore EmptyGeneralCatchClause
                    {
                    }

                    try
                    {
                        qThread.Abort();
                    }
                    // ReSharper disable EmptyGeneralCatchClause
                    catch (Exception)
                    // ReSharper restore EmptyGeneralCatchClause
                    {
                    }

                    MessageBox.Show("Key generating error: timeout.\r\n\r\nIs your bit length too large?", "Error");

                    break;
                }
            }


            // If we found numbers, we continue to create
            if (p.GetFoundPrime() && q.GetFoundPrime())
            {
                BigInteger n     = p.GetPrimeNumber() * q.GetPrimeNumber();
                BigInteger euler = (p.GetPrimeNumber() - 1) * (q.GetPrimeNumber() - 1);

                this.Dispatcher.Invoke((Action)(() =>
                {
                    messageStatusBar.Text = "Generating e prime number ...";
                }));

                var primeNumber = new PrimeNumber();

                while (true)
                {
                    primeNumber.SetNumber(Generator.Random(2, euler - 1));

                    start = DateTime.Now;

                    eThread = new Thread(primeNumber.RabinMiller);
                    eThread.Start();

                    while (eThread.IsAlive)
                    {
                        TimeSpan ts = DateTime.Now - start;

                        if (ts.TotalMilliseconds > (1000 * 60 * 5))
                        {
                            MessageBox.Show("Key generating error: timeout.\r\n\r\nIs your bit length too large?", "Error");

                            break;
                        }
                    }

                    if (primeNumber.GetFoundPrime() && (BigInteger.GreatestCommonDivisor(primeNumber.GetPrimeNumber(), euler) == 1))
                    {
                        break;
                    }
                }

                if (primeNumber.GetFoundPrime())
                {
                    this.Dispatcher.Invoke((Action)(() =>
                    {
                        messageStatusBar.Text = "Calculating key components ...";
                    }));

                    // Calculate secret exponent D as inverse number of E
                    BigInteger d = MathExtended.ModularLinearEquationSolver(primeNumber.GetPrimeNumber(), 1, euler);
                    //BigInteger d = MathExtended.ModularLinearEquationSolver(83, 1, 120);

                    // Displaying keys
                    if (d > 0)
                    {
                        // N
                        (keysVM as KeysVM).PublicN  = n.ToString();
                        (keysVM as KeysVM).PrivateN = n.ToString();

                        // E
                        (keysVM as KeysVM).PublicE = primeNumber.GetPrimeNumber().ToString();

                        // D
                        (keysVM as KeysVM).PrivateD = d.ToString();

                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            tabControl.SelectedIndex = 2;

                            messageStatusBar.Text = "Successfully created key pair.";
                        }));
                    }
                    else
                    {
                        this.Dispatcher.Invoke((Action)(() =>
                        {
                            messageStatusBar.Text = "Error: Modular equation solver fault.";
                        }));

                        MessageBox.Show(
                            "Error using mathematical extensions.\r\ne = " + primeNumber + "\r\neuler = " + euler + "\r\np = " +
                            p.GetPrimeNumber() + "\r\n" + q.GetPrimeNumber(), "Error");
                    }
                }
            }
            else
            {
                this.Dispatcher.Invoke((Action)(() =>
                {
                    messageStatusBar.Text = "Idle";
                }));
            }
            this.Dispatcher.Invoke((Action)(() =>
            {
                this.progressBar.IsIndeterminate = false;
            }));
        }
Example #22
0
        /// <summary>
        /// Main Thread
        /// </summary>
        static void Main()
        {
            PrimeNumber.CalculateTermsUntilValue(MAX_VALUE);

            Console.WriteLine("Solution: {0}", PrimeNumber.GetListPrimes().Where(p => (p < MAX_VALUE)).Sum());
        }
        public void TestIf25404451IsPrimeNumber()
        {
            var pn = new PrimeNumber(25404451);

            Assert.IsTrue(pn.IsPrime());
        }
Example #24
0
 public void PrimeNumber_IsTrue()
 {
     Assert.IsTrue(PrimeNumber.isPrime(5));
 }
Example #25
0
 public void LargeNumber_IsFalse()
 {
     Assert.IsFalse(PrimeNumber.isPrime(547862));
 }
Example #26
0
 public void Test1()
 {
     var dd = PrimeNumber.GetAllPrimeNumbers(Enumerable.Range(1, 49).ToList());
 }
Example #27
0
 public long Index(int nThPrimeNumber)
 {
     return(PrimeNumber.FindNthPrimeNumber(nThPrimeNumber));
 }
Example #28
0
 static void Main(string[] args)
 {
     PrimeNumber.CheckPrimeNumber();
     Console.WriteLine(Fibo.CountFibonachi(Fibo.GetNumber()));
     Console.ReadKey();
 }
        public void TestIfNotIsPrimeNumber()
        {
            var pn = new PrimeNumber(6);

            Assert.IsFalse(pn.IsPrime());
        }
Example #30
0
 public PrimeNumberTest()
 {
     _primeNumber = new PrimeNumber();
 }
        public void TestIfIsPrimeNumber()
        {
            var pn = new PrimeNumber(7);

            Assert.IsTrue(pn.IsPrime());
        }
Example #32
0
        /// <summary>
        /// continua calcolo numeri primi da ultimo su db
        /// </summary>
        public async void ContinuosCalc()
        {
            //inizializza flag e segna punto da cui ripartire
            InitFlag();
            //il semaforo ha un posto "attivo" per un massimo di due totali
            //edit (update ram) tre posti per un massimo di tre
            sem = new Semaphore(3, 3);
            List <PrimeNumber> container = new List <PrimeNumber>();

            do
            {
                Thread[] th = new Thread[3];

                //faccio partire tre thread
                for (int i = 0; i < th.Length; i++)
                {
                    //segment = porzione di numeri da analizzare
                    long segment = this.flag + 100000;

                    //inizializza thread per
                    th[i] = new Thread(new ThreadStart(() =>
                    {
                        //fa entrare un thread alla volta
                        sem.WaitOne();
                        //controlla numeri da proflag fino a flag+2000
                        for (long ind = this.flag; ind <= segment; ind++)
                        {
                            if (IsPrime(ind) == true)
                            {
                                PrimeNumber p = new PrimeNumber();
                                p.IDN         = ind;
                                //se รจ primo lo sbatte in lista
                                container.Add(p);
                            }
                        }
                        //libera un posto
                        sem.Release(1);
                    }
                                                       ));
                    //thread partono
                    th[i].Start();
                    //attende gli altri prima di continuare
                    th[i].Join();
                    this.flag += 100000;
                }

                //ordina lista
                SortPrimeList(container);

                try
                {
                    //cerca di persistere
                    await gnome.PersistPrimeAsync(container).ConfigureAwait(false);

                    container.Clear();
                    //incrementa di segment*3 (ogni thread controlla 2000n)
                    this.flag += 300000;
                }
                catch (Win32Exception win32_ex)
                {
                    //ci riprova
                    await gnome.PersistPrimeAsync(container);

                    container.Clear();
                    this.flag += 300000;
                }
                catch (SqlException s_ex)
                {
                    //ci riprova
                    await gnome.PersistPrimeAsync(container);

                    container.Clear();
                    this.flag += 300000;
                }
            } while (this.flag < long.MaxValue);
        }