Didart

Sum Prime Non Prime - Nested Loops

Apr 19th, 2022
917
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function sumPrimeNonPrime(input) {
  2.     let index = 0;
  3.     let primeNums = 0;
  4.     let nonPrimeNums = 0;
  5.  
  6.     while (input[index] !== 'stop') {
  7.         let num = Number(input[index]);
  8.  
  9.         if (num < 0) {
  10.             console.log(`Number is negative.`);
  11.         } else {
  12.             let isPrime = true;
  13.             for (let i = 2; i < num; i++) {
  14.  
  15.                 if (num % i == 0) {
  16.                     isPrime = false;
  17.                     break;
  18.                 }
  19.             }
  20.  
  21.             if (isPrime) {
  22.                 primeNums += num;
  23.             } else {
  24.                 nonPrimeNums += num;
  25.             }
  26.         }
  27.         index++;
  28.     }
  29.  
  30.     console.log(`Sum of all prime numbers is: ${primeNums}`);
  31.     console.log(`Sum of all non prime numbers is: ${nonPrimeNums}`);
  32.  
  33. }
  34.  
  35. sumPrimeNonPrime(["3", "9", "0", "7", "19", "4", "stop"])
  36.  
  37.  
  38.  
Advertisement
Add Comment
Please, Sign In to add comment