Exemple #1
0
        /// <summary>
        /// Finds the largest prime factor of num
        /// </summary>
        /// <param name="num">Number to find the largest prime factor for</param>
        /// <returns>Largest prime factor of num or 0 if none found</returns>
        public static long LargestPrimeFactor(long num)
        {
            if (num <= 1)
            {
                return(0);
            }
            else if (num == 2)
            {
                return(2);
            }
            else
            {
                long largest = 0;

                long sqrtNum = (long)Math.Ceiling(Math.Sqrt((double)num));

                // Check all odd numbers if they're a factor -and- they're a prime number
                for (long i = 3; i <= sqrtNum; i += 2)
                {
                    if ((num % i == 0) && Mathx.IsPrime(i))
                    {
                        largest = i;
                    }
                }

                // Check if num itself is a prime number (by definition, it's already a factor of itself)
                if (Mathx.IsPrime(num))
                {
                    largest = num;
                }

                return(largest);
            }
        }
Exemple #2
0
        /// <summary>
        /// Get the nth prime number
        /// </summary>
        /// <example>
        /// By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
        /// </example>
        /// <param name="n">Sequence number of primes</param>
        /// <returns>nth prime or -1 if we're out of bounds</returns>
        public static long NthPrime(int n)
        {
            int  numPrimes = 0;
            long num       = 2;

            while ((numPrimes < n) && (num < long.MaxValue))
            {
                if (Mathx.IsPrime(num))
                {
                    numPrimes++;
                }

                if (numPrimes == n)
                {
                    return(num);
                }

                num++;
            }

            return(-1);
        }