Created
August 24, 2017 02:40
-
-
Save rushilsrivastava/f1fc22a0b01a563f70427194080bc5eb to your computer and use it in GitHub Desktop.
A simple java program that takes a number, and prints that many primes.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.rushilsrivastava.prime; | |
import java.util.Scanner; | |
public class PrimeByNumber { | |
public static void main(String[] args) { | |
System.out.println("How many prime numbers would you like to calculate? "); | |
Scanner sc = new Scanner(System.in); | |
int numbers = sc.nextInt(); | |
//loop through the numbers one by one | |
int counter = 0; | |
int i = 0; | |
while (counter < numbers) { | |
boolean isPrime = isPrime((long) i); | |
// print the number | |
if (isPrime) { | |
System.out.print(i + " "); | |
counter++; | |
} | |
i++; | |
} | |
} | |
public static boolean isPrime(long n) { | |
if (n < 2) return false; | |
if (n == 2 || n == 3) return true; | |
if (n % 2 == 0 || n % 3 == 0) return false; | |
long sqrtN = (long) Math.sqrt(n) + 1; | |
for (long i = 6L; i <= sqrtN; i += 6) { | |
if (n % (i - 1) == 0 || n % (i + 1) == 0) return false; | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment