Write a program to print first 500 Special numbers.
Answers
package crunchify.com.tutorial;
import java.util.Scanner;
/**
* @author Crunchify.com
* Program: Java program to print Sum of First 500 Prime numbers (or First N Prime numbers)
* Version: 1.0.1
*
*/
public class CrunchifySumOfNPrimeNumbers {
public static void main(String args[]) {
CrunchifySumOfNPrimeNumbers object = new CrunchifySumOfNPrimeNumbers();
object.sumFirst500Prime();
@SuppressWarnings("resource")
Scanner reader = new Scanner(System.in); // Reading from System.in
System.out.println("\nEnter a number: ");
int myNumber = reader.nextInt();
int crunchifyStartNumber = 2;
int counter = 1;
int crunchifySum = 0;
while (counter <= myNumber) {
if (checkIfPrimeNumber(crunchifyStartNumber)) {
crunchifySum += crunchifyStartNumber;
counter++;
}
crunchifyStartNumber++;
}
println("Sum of first " + myNumber + " Prime numbers: " + crunchifySum);
}
private void sumFirst500Prime() {
int crunchifyStartNumber = 2;
int counter = 1;
long crunchifySum = 0;
while (counter <= 500) {
if (checkIfPrimeNumber(crunchifyStartNumber)) {
crunchifySum += crunchifyStartNumber;
counter++;
}
crunchifyStartNumber++;
}
println("Sum of first " + 500 + " Prime numbers: " + crunchifySum);
}
// Simple Println Utility
private static void println(String crunchifySum) {
System.out.println(crunchifySum);
}
// PrimeNumber Check Utility
private static boolean checkIfPrimeNumber(int primeNumber) {
for (int i = 2; i <= primeNumber / 2; i++) {
if (primeNumber % i == 0) {
return false; // Nope.. it's not a prime number
}
}
return true; // Yup.. it's prime number
}
Explanation:
Sum of first 500 Prime numbers: 824693
Enter a number:
800
Sum of first 800 Prime numbers: 2277959