分享

PTA 素数对猜想 C#版

 悟道习术 2021-03-14

using System;

using System.Collections.Generic;

namespace Prime

{

    class Program

    {

      static   void Main(string[] args)

        {

            while (true)

            {

                System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

                List<int> listPrime;

                listPrime = new List<int>();

                Console.WriteLine("请输入一个正整数!");

                String input = Console.ReadLine();

                stopwatch.Start();

                int no = Convert.ToInt32(input);

                int count = 0;

                listPrime.Add(2); 

                for (int i = 2; i <= no; i++)

                {

                    if (i % 2 == 0 )//除2以外,所有质数都是奇数,故如此

                    {

                        continue;

                    }

                    else

                    {

                        if (isPrime(i, ref listPrime))

                        {

                            if (listPrime.Count >= 2)

                            {

                                if (listPrime[listPrime.Count - 1] - listPrime[listPrime.Count - 2] == 2)

                                {

                                   Console.WriteLine(listPrime[listPrime.Count - 1]+"----"+ listPrime[listPrime.Count - 2]);

                                    count++;

                                };

                            }

                        }

                    }

                }

                stopwatch.Stop();

                Console.WriteLine(stopwatch.Elapsed.TotalMilliseconds);

                Console.WriteLine(stopwatch.Elapsed.TotalSeconds);

                Console.WriteLine(count);

            }

        }

      static  bool isPrime( int No,ref List<int> listPrime)//将找到的素数置于listPrime中

        {

            bool b = false;

            foreach (var prime in listPrime)

            {

                if (No%prime==0)

                {

                    b= false;

                    break;

                }

                if (prime>Math.Sqrt(No))

                {

                    b= true;

                    listPrime.Add(No);

                    break;

                }

            }

            return b;

        }

    }

}

以上为C#版的素数对猜想代码。但在PTA上作答时,不要写黄色背景部分,由于其太傻瓜化,它会判定其错误的。

另判断素数的逻辑,有一些思想是来源于知乎大神指点。链接如下https://zhuanlan.zhihu.com/p/46389152  文中一些思想比较实用。

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多