-1

Write a program that goes through all the numbers from 1 to 50 and for each one prints on the screen if the number is even or odd. If the number is also prime, the program should say you are cousin.

I can't think of a way to run the code so that it prints the even, odd, and prime numbers together. Example: 1 Odd 2 Prime and Pair 3 Prime and Odd 4 Pair

I only solved part of this problem.

function nPrime(n){
    if(n == 1) return false;
    
    for(var i = 2; i < n; i++){
        if(n % i == 0) return false;
    }
    return true;
}

let num = 50;

for(var i = 1; i <= num; i++){
    if(nPrime(i)){
        console.log(i + " Prime");
    }
}
  • Welcome to SO! What is your question? Where are you stuck? – WOUNDEDStevenJones Jul 22 '22 at 20:31
  • I can't think of a way to run the code so that it prints the even, odd, and prime numbers together. Example: 1 Odd 2 Prime and Pair 3 Prime and Odd – f2lpOliveira Jul 22 '22 at 20:34
  • Here. you were looking for more than just if its odd: function nPrime(n){ if(n == 1) return false; for(var i = 2; i < n; i++){ if(n % i == 0) return false; } return true; } let num = 50; for(var i = 1; i <= num; i++){ str = i; if(i % 2 == 0){ str += " Even"; } else{ str += " Odd"; } if(nPrime(i)){str += " Prime";} console.log(str) } – imvain2 Jul 22 '22 at 20:50

1 Answers1

0

function isEvem(num) {
    return (num % 2) === 0
}

function isPrime(num) {
    if (num === 2) {
        return true;
    }
    if (num > 1) {
        for (var i = 2; i < num; i++) {
            if (num % i !== 0) {
                return true;
            } else if (num === i * i) {
                return false
            } else {
                return false;
            }
        }
    }
    return false;
}
 
/** Main function */
function checkTill(num) {
    for (var i = 1; i <= num; i++) {
        
        let result = [];
        // will always be even or odd
        result.push(isEvem(i) ? 'Even' : 'Odd');
        
        if (isPrime(i)) {
            result.push('Prime')
        }

        // let join handle logic to add 'and' or not
        console.log(i, result.join(' and '))
    }
}

/** Call */
checkTill(10);
vaira
  • 2,191
  • 1
  • 10
  • 15