`
阿尔萨斯
  • 浏览: 4146127 次
社区版块
存档分类
最新评论

C# - 求100的阶乘结果中从左到右的第一个4位的质数

 
阅读更多

// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Program.cs" company="Chimomo's Company">
// Respect the work.
// </copyright>
// <summary>
// The program.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace CSharpLearning
{
    using System;

    /// <summary>
    /// The program.
    /// </summary>
    public static class Program
    {
        /// <summary>
        /// The main.
        /// </summary>
        /// <param name="args">
        /// The args.
        /// </param>
        public static void Main(string[] args)
        {
            string fac100 = Factorial(100).ToString("F0");
            Console.WriteLine("The factorial of 100 is : {0}", fac100);
            for (int i = 0; i <= fac100.Length - 4; i++)
            {
                string substr = fac100.Substring(i, 4);
                if (CheckPrime(Convert.ToInt32(substr)))
                {
                    Console.WriteLine("The expected result found and it is : " + substr);
                    return;
                }
            }

            Console.WriteLine("No result as expected!!");
        }

        /// <summary>
        /// The factorial.
        /// </summary>
        /// <param name="n">
        /// The n.
        /// </param>
        /// <returns>
        /// The <see cref="double"/>.
        /// </returns>
        public static double Factorial(int n)
        {
            double result = 1;
            for (int i = 1; i <= n; i++)
            {
                result *= i;
            }

            return result;
        }

        /// <summary>
        /// The check prime.
        /// </summary>
        /// <param name="n">
        /// The n.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public static bool CheckPrime(int n)
        {
            if (n == 1 || n == 2)
            {
                return true;
            }

            int squareRoot = Convert.ToInt32(Math.Sqrt(n));
            for (int i = squareRoot; i > 1; i--)
            {
                if (n % i == 0)
                {
                    return false;
                }
            }

            return true;
        }
    }
}

// Output:
/*
The factorial of 100 is : 93326215443944100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
The expected result found and it is : 2621
*/
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics