LoginSignup
0
2

More than 5 years have passed since last update.

そすう

Last updated at Posted at 2018-02-10

最速で素数を求めるほにゃららが酷かったので
以下

第一引数までの素数をコンソールに出力

prim.cs
namespace ConsoleApplication1
{
    class Program
    {
        private static int input;
        private static bool[] sieve;
        private static int limitSqrt;

        static void Main(string[] args)
        {
            input = int.Parse(args[0]);
            sieve = new bool[input + 1];
            limitSqrt = (int)System.Math.Sqrt((double)input);

            sieve[0] = false;
            sieve[1] = false;
            sieve[2] = true;
            sieve[3] = true;

            for (int x = 1 ; x <= limitSqrt ; x++)
            {
                for (int y = 1 ; y <= limitSqrt ; y++)
                {
                    int n = (4 * x * x) + (y * y);
                    if (n <= input && (n % 12 == 1 || n % 12 == 5))
                    {
                        sieve[n] = !sieve[n];
                    }
                    n = (3 * x * x) + (y * y);
                    if (n <= input && (n % 12 == 7))
                    {
                        sieve[n] = !sieve[n];
                    }
                    n = (3 * x * x) - (y * y);
                    if (x > y && n <= input && (n % 12 == 11))
                    {
                        sieve[n] = !sieve[n];
                    }
                }
            }
            for (int m = 5; m <= limitSqrt; m++)
            {
                if (sieve[m])
                {
                    int m2 = m * m;
                    for (int i = m2; i <= input ; i += m2)
                    {
                        sieve[i] = false;
                    }
                }
            }
            for (int i = 0 ; i <= input ; i++)
            {
                if (sieve[i])
                {
                    System.Console.Write(i.ToString() + ",");
                }
            }
        }
    }
}
0
2
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2