Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Scanner;
- public class SumPrimeNonPrime {
- public static void main(String[] args) {
- Scanner scanner = new Scanner(System.in);
- int primeSum = 0;
- int nonPrimeSum = 0;
- /**
- * PRIME NUMBER - a number that is divisible only by itself and 1 (e.g. 2, 3, 5, 7, 11).
- * NON PRIME NUMBER - non-prime numbers are divisible by more than two numbers.
- */
- String command = scanner.nextLine();
- while(!command.equals("stop")) {
- int currentNum = Integer.parseInt(command);
- // check for negative number
- if(currentNum < 0){
- System.out.println("Number is negative.");
- command = scanner.nextLine();
- continue;
- }
- // save count of dividers
- int dividersCount = 0;
- for (int i = 1; i <= currentNum; i++) {
- // check if num is divisible
- if(currentNum % i == 0) {
- dividersCount++;
- }
- }
- // check if number is prime or non prime
- if(dividersCount > 2) {
- nonPrimeSum = nonPrimeSum + currentNum;
- } else{
- primeSum = primeSum + currentNum;
- }
- command = scanner.nextLine();
- }
- System.out.printf("Sum of all prime numbers is: %d%n", primeSum);
- System.out.printf("Sum of all non prime numbers is: %d", nonPrimeSum);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement