Advertisement
GabrielHr00

SumPrimeNonPrime

Dec 5th, 2022
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.52 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. int primeSum = 0;
  7. int nonPrimeSum = 0;
  8.  
  9. /**
  10. * PRIME NUMBER - a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).
  11. * NON PRIME NUMBER - non-prime numbers are divisible by more than two numbers.
  12. */
  13.  
  14. String command = scanner.nextLine();
  15. while(!command.equals("stop")) {
  16. int currentNum = Integer.parseInt(command);
  17.  
  18. // check for negative number
  19. if(currentNum < 0){
  20. System.out.println("Number is negative.");
  21. command = scanner.nextLine();
  22. continue;
  23. }
  24.  
  25. // save count of dividers
  26. int dividersCount = 0;
  27. for (int i = 1; i <= currentNum; i++) {
  28. // check if num is divisible
  29. if(currentNum % i == 0) {
  30. dividersCount++;
  31. }
  32. }
  33.  
  34. // check if number is prime or non prime
  35. if(dividersCount > 2) {
  36. nonPrimeSum = nonPrimeSum + currentNum;
  37. } else{
  38. primeSum = primeSum + currentNum;
  39. }
  40.  
  41. command = scanner.nextLine();
  42. }
  43.  
  44. System.out.printf("Sum of all prime numbers is: %d%n", primeSum);
  45. System.out.printf("Sum of all non prime numbers is: %d", nonPrimeSum);
  46.  
  47. }
  48. }
  49.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement