Advertisement
Guest User

Untitled

a guest
Oct 25th, 2018
326
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.25 KB | None | 0 0
  1. import java.util.Scanner;
  2.  
  3. public class SumPrimeNonPrime {
  4.     public static void main(String[] args) {
  5.         Scanner scanner = new Scanner(System.in);
  6.         long sumPrimeNumbers = 0;
  7.         long sumNonPrimeNumbers = 0;
  8.  
  9.         String input = scanner.nextLine();
  10.         while (!input.equals("stop")) {
  11.  
  12.             int number = Integer.parseInt(input);
  13.             if (number < 0) {
  14.                 System.out.println("Number is negative.");
  15.             } else {
  16.                 if (isPrime(number)) {
  17.                     sumPrimeNumbers += number;
  18.                 } else {
  19.                     sumNonPrimeNumbers += number;
  20.                 }
  21.             }
  22.             input = scanner.nextLine();
  23.         }
  24.         System.out.println("Sum of all prime numbers is: " + sumPrimeNumbers);
  25.         System.out.println("Sum of all non prime numbers is: " + sumNonPrimeNumbers);
  26.     }
  27.  
  28.     private static boolean isPrime(int num) {
  29.         boolean isPrime = true;
  30.         if (num < 2) isPrime = false;
  31.         else {
  32.             for (int i = 2; i <= Math.sqrt(num); i++) {
  33.                 if (num % i == 0) {
  34.                     isPrime = false;
  35.                     break;
  36.                 }
  37.             }
  38.         }
  39.         return isPrime;
  40.     }
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement