Tuesday, February 21, 2017

Prime Number Optimization

Sample Code:


package com.rizvi.so;

import java.util.Scanner;

public class PrimeCheck {

    public static void main(String[] args) {
        Scanner inp = new Scanner(System.in);
        PrimeCheck primeChecker = new PrimeCheck();
        System.out.println("Give Input: ");
        int candidate = inp.nextInt();
        System.out.println(candidate+" is prime: "+primeChecker.isPrime(candidate));
    }

    // checks whether an int is prime or not.
    boolean isPrime(int n) {
        // check if n is 2
        if (n == 2)
            return true;
        // check if n is a multiple of 2
        if (n < 2 || n % 2 == 0)
            return false;
        // if not, then just check the odds
        for (int i = 3; i * i <= n; i += 2) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
}

Output:

Give Input:
31
31 is prime: true

Resource Link:


  1. http://introcs.cs.princeton.edu/java/14array/PrimeSieve.java.html

No comments:

Post a Comment