Advertisement
veronikaaa86

03. Sum Prime Non Prime

Dec 5th, 2021
260
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.24 KB | None | 0 0
  1. package nestedLoops;
  2.  
  3. import java.util.Scanner;
  4.  
  5. public class P03SumPrimeNonPrime {
  6. public static void main(String[] args) {
  7. Scanner scanner = new Scanner(System.in);
  8.  
  9. int primeSum = 0;
  10. int nonPrimeSum = 0;
  11.  
  12. String input = scanner.nextLine();
  13. while (!input.equals("stop")) {
  14. int currentNum = Integer.parseInt(input);
  15.  
  16. if (currentNum < 0) {
  17. System.out.println("Number is negative.");
  18. input = scanner.nextLine();
  19. continue;
  20. }
  21.  
  22. int count = 0;
  23. for (int i = 1; i <= currentNum; i++) {
  24. if (currentNum % i == 0) {
  25. count++;
  26. }
  27. }
  28.  
  29. if (count == 2) {
  30. //числото е просто
  31. primeSum = primeSum + currentNum;
  32. } else {
  33. //числото не е просто
  34. nonPrimeSum = nonPrimeSum + currentNum;
  35. }
  36.  
  37. input = scanner.nextLine();
  38. }
  39.  
  40. System.out.printf("Sum of all prime numbers is: %d%n", primeSum);
  41. System.out.printf("Sum of all non prime numbers is: %d%n", nonPrimeSum);
  42. }
  43. }
  44.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement