LoginSignup
1
1

More than 5 years have passed since last update.

Unityで素数を求めてみた

Posted at

nSearchNum個数分の素数がnResult配列に入ります。
素数は「平方根より小さい素数の倍数ではない」らしいです。

Calc.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Calc : MonoBehaviour {
    public int nSearchNum = 100;

    // Use this for initialization
    void Start () {
        StartCoroutine (Calcurate ());
    }

    // Update is called once per frame
    void Update () {

    }

    IEnumerator Calcurate() {
        int nPercent = (nSearchNum / 100) > 100 ? (nSearchNum / 100) : 100;
        float startTime = Time.time;
        int nInsIdx = 0;
        int[] nResult = new int[nSearchNum];
        nResult [nInsIdx++] = 2;
        int nTgtIdx = 0;
        int nMin = 3;
        bool bSosuu = false;
        while (nTgtIdx < nSearchNum) {
            int nMax = nResult [nTgtIdx] * nResult [nTgtIdx];
            for (int n = nMin; n < nMax; n++) {
                bSosuu = true;
                for (int i = 0; i <= nTgtIdx; i++) {
                    if ((n % nResult [i]) == 0) {
                        bSosuu = false;
                        break;
                    }
                }
                if (bSosuu) {
                    nResult [nInsIdx++] = n;
                    if (nInsIdx >= nSearchNum) {
                        Debug.Log ("[" + nInsIdx + "] " + n+" (" + (Time.time-startTime).ToString() + "sec)");
                        yield break;
                    }
                    if ((nInsIdx % nPercent) == 0) {
                        yield return null;
                        Debug.Log ((nInsIdx * 100 / nSearchNum).ToString() + "% (" + (Time.time-startTime).ToString() + "sec)");
                    }
                }
            }
            nTgtIdx++;
            nMin = nMax + 1;
        }

        yield break;
    }
}
1
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
1
1