Advertisement
GabrielHr00

03. Sum Prime Non Prime

Feb 9th, 2025
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.15 KB | None | 0 0
  1. package nestedLoops_Exercise;
  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 sumNonPrime = 0;
  9.         int sumPrime = 0;
  10.  
  11.         String command = scanner.nextLine();
  12.         while (!command.equals("stop")) {
  13.             int num = Integer.parseInt(command);
  14.  
  15.             if (num < 0) {
  16.                 System.out.printf("Number is negative.%n");
  17.                 command = scanner.nextLine();
  18.                 continue;
  19.             }
  20.             int dividersCount = 0;
  21.  
  22.             for (int i = 1; i <= num; i++) {
  23.                 if (num % i == 0) {
  24.                     dividersCount++;
  25.                 }
  26.             }
  27.  
  28.             if (dividersCount > 2) {
  29.                 // non prime
  30.                 sumNonPrime += num;
  31.             } else {
  32.                 // prime
  33.                 sumPrime += num;
  34.             }
  35.  
  36.             command = scanner.nextLine();
  37.         }
  38.  
  39.         System.out.printf("Sum of all prime numbers is: %d\n" +
  40.                 "Sum of all non prime numbers is: %d", sumPrime, sumNonPrime);
  41.     }
  42. }
  43.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement