Advertisement
GabrielHr00

03. Sum Prime Non Prime

Jun 18th, 2023
246
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.17 KB | None | 0 0
  1. package S6_NestedLoops;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class SumPrimeNonPrime {
  6.     public static void main(String[] args) {
  7.         Scanner scanner = new Scanner(System.in);
  8.         int sumPrimeNumbers = 0;
  9.         int sumNonPrimeNumbers = 0;
  10.  
  11.         String command = scanner.nextLine();
  12.         while (!command.equals("stop")) {
  13.             int currentNum = Integer.parseInt(command);
  14.             int dividersCount = 0;
  15.  
  16.             if (currentNum < 0) {
  17.                 System.out.println("Number is negative.");
  18.                 command = scanner.nextLine();
  19.                 continue;
  20.             }
  21.  
  22.             for (int i = 1; i <= currentNum; i++) {
  23.                 if(currentNum % i == 0) {
  24.                     dividersCount++;
  25.                 }
  26.             }
  27.  
  28.             if(dividersCount > 2) {
  29.                 sumNonPrimeNumbers += currentNum;
  30.             } else {
  31.                 sumPrimeNumbers += currentNum;
  32.             }
  33.             command = scanner.nextLine();
  34.         }
  35.        
  36.         System.out.printf("Sum of all prime numbers is: %d%n" +
  37.                 "Sum of all non prime numbers is: %d", sumPrimeNumbers, sumNonPrimeNumbers);
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement