0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

n番目の双子素数を求めるプラグラム

Posted at

古河機械金属株式会社の広告を見かけたフォロワーに巻き込まれましたので簡単解けるプログラムをC#で書きました。
解説省略ですが、12番めは149と151になるので、150周年らしいです。多分


public static class PrimeFinder
{
    public static void Main()
    {
        Console.WriteLine("双子素数を求めるプログラムです。n番目の双子素数を求めます。");
        bool isnum = false;
        int num = 0;
        var input = Console.ReadLine();
        while (!isnum)
        {
            try
            {
                num = Int32.Parse(input);
                isnum = true;
            }
            catch
            {
                Console.WriteLine("数字を入力してください");
                input = Console.ReadLine();
            }
        }
        int primenumber = 3;
        int count = 0;
        while (true)
        {
            if (IsPrimenumber(primenumber) && IsPrimenumber(primenumber + 2))
            {
                count++;
            }
            if (count == num)
            {
                Console.WriteLine($"{num}番目の双子素数は{primenumber}{primenumber + 2}です。");
                break;
            }
            primenumber += 2; // 双子素数は奇数なので、2ずつ増やす
            if (primenumber > 1000000) // 上限を設定
            {
                Console.WriteLine("指定された範囲内に双子素数が見つかりませんでした。");
                break;
            }


        }
        Console.WriteLine("任意のキーを入力してください");
        Console.ReadKey();

        bool IsPrimenumber(int num)
        {
            for (int i = 2; i * i <= num; ++i)
            {
                if (num % i == 0)
                {
                    return false;
                }
            }
            return true;
        }

    }
}

0
1
0

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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?