Counting the Number of Primes Entered in Java

Problem:

Write a program that reads positive integers from the keyboard until the user enters 0. Then the program prints the number of prime numbers entered.

Output:

Enter prime numbers seperated by space(0 to quit):
2 3 5 03


Solution:

import java.util.Scanner;

public class lauprob5

{
 public static void main(String[] args) 
 
 {
  Scanner scan = new Scanner (System.in);
  
     //We need something to use to get into the loop
     int prime = 1, count = 0;
     
     System.out.println("Enter prime numbers seperated by space(0 to quit):");
     
     //We'll keep on looping and scanning till we scan a 0
     while (prime != 0)
      
     {
      
     prime = scan.nextInt();
     
     //It's easier to prove that a number that we think is prime
     // isn't really prime because a prime is a number that's
     //only divisible by one and itself
     //so we'll make our initial boolean: 
     boolean isPrime = true; 
     
     //there are no prime numbers less than 2 so we need this
     //to quickly prove that a number isn't prime, so how easy
     //to prove that a number isn't prime?
     if (prime < 2) isPrime = false; 
     
     for (long i = 2; i*i <= prime; i++)
      
     { 
      //if the prime is divisble by i, which a number
      //that is neither 1 or the entered number, then 
      //the number is NOT prime and the case is closed (break)
       if (prime % i == 0) 
       
       isPrime = false; 
      break; 
     } 
     
     //If after existing that loop, we never found 
     //any divisors of the number (and it's not less than true
     //then it is of course a prime number so we should
     //increase our variable that counts the number of scanned
     //prime numbers by one
     if (isPrime) 
      
      count ++;
     }
     System.out.print(count);
     } 
 }


No comments :

Post a Comment

Follow Me

If you like our content, feel free to follow me to stay updated.

Subscribe

Enter your email address:

We hate spam as much as you do.

Upload Material

Got an exam, project, tutorial video, exercise, solutions, unsolved problem, question, solution manual? We are open to any coding material. Why not upload?

Upload

Copyright © 2012 - 2014 Java Problems  --  About  --  Attribution  --  Privacy Policy  --  Terms of Use  --  Contact