get Some Primes - Java java.lang

Java examples for java.lang:int prime

Description

get Some Primes

Demo Code


//package com.java2s;
import java.util.ArrayList;

import java.util.List;

public class Main {
    public static List<Integer> getSomePrimes(int numberOfPrimes) {
        List<Integer> primes = new ArrayList<Integer>();
        if (numberOfPrimes < 1) {
            return primes;
        }//from   w  w  w  .  j  av a 2s  .  c  om
        primes.add(2);
        for (int candidate = 3; primes.size() < numberOfPrimes; candidate += 2) {
            boolean isPrime = true;
            int limit = (int) Math.sqrt(candidate);
            for (int prime : primes) {
                if (candidate % prime == 0) {
                    isPrime = false;
                    break;
                }
                if (prime > limit) {
                    break;
                }
            }
            if (isPrime) {
                primes.add(candidate);
            }
        }
        return primes;
    }
}

Related Tutorials