0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

素数判定プログラム

Last updated at Posted at 2025-02-20

はじめに

転職の応募に際し、コーディング試験があるため、復習として素数判定プログラムを書いてみた。
ある自然数nが素数であるかを判別します。
素数であればtrueを、素数でなければfalseを返します。

コード

public class Main {
    public static void main(String[] args) {
        System.out.println(isPrime(25));  // false
        System.out.println(isPrime(31));  // true
        System.out.println(isPrime(169));  // false
        System.out.println(isPrime(167));  // true
    }
    
    public static boolean isPrime(int n) {

        if (n == 1) {
            return false;
        }

        if (n == 2) {
            return true;
        }

        if (n % 2 == 0) {
            return false;
        } 

        int sqrt = (int) Math.sqrt(n);

        if (n == sqrt*sqrt) {
          return false;
        }
        
        for (int i = 3; i <= sqrt; i += 2) {
            if (n % i == 0) {
                return false;
            }
        }
        
        return true;
    }
}

解説

1は素数ではないので、falseを返す。

if (n == 1) {
    return false;
}

2は素数なので、trueを返す。

if (n == 2) {
    return true;
}

2を除いた偶数は素数ではないので、falseを返す。

if (n % 2 == 0) {
    return false;
} 

数値nが素数かどうかは、nの平方根まで調べれば十分である。

nの平方根が自然数のとき、素数ではないので、falseを返す。

int sqrt = (int) Math.sqrt(n);

if (n == sqrt*sqrt) {
  return false;
}

2より大きい偶数は素数ではないことはわかっているので、i3から2ずつ増やして素数の判別を行う。

for (int i = 3; i <= sqrt; i += 2) {
    if (n % i == 0) {
        return false;
    }
}

上記すべてに当てはまらなければ、trueを返す。

return true;

まとめ

計算量 $O(n^{1/2})$ で素数の判別ができる。

0
0
2

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?