Home > OS >  Cheking if it's a prime number with JS
Cheking if it's a prime number with JS

Time:03-05

I'm first trying to push only prime numbers (without 2) to an array and then sum them all but getting undefined.

I've been working on this for long days, I'd appreciate if anyone could help me.

let letsCheck = () => {

    let ourList = []
    let sum = 0

    for(let i = 2; i <= 50; i  ) {
        if(i % 2 !== Number.isInteger()) {
            ourList.push(Number(i))
        }           
    }
    
    for(let prime in ourList) {
        sum  = ourList[prime]
    }
}

CodePudding user response:

First of all, You are not checking prime but checking odd numbers by % operator.

Second, you are checking Number.isNumber function which will return the boolean so, the comparison have some issues.

Here is one solution which may help.

let letsCheck = () => {

    let ourList = []
    let sum = 0

    for(let i = 3; i <= 50; i  ) {
        if(isPrimeNumber(i)) {
            ourList.push(Number(i))
        }           
    }
    
    for(let prime in ourList) {
        sum  = ourList[prime]
    }
}

const isPrimeNumber = number => {
    for(let i = 2; i <= Math.ceil(number/2); i  ) {
        if(number % 2 === 0) {
            return false;
        }
    }

    return true;
}

CodePudding user response:

From, your code, it was more likely for obtaining odd/even numbers instead of prime numbers.

Prime numbers are whole numbers greater than 1, that have only two factors – 1 and the number itself

Odd numbers are the numbers that doesn't have 2 as its factor, and will have remainder = 1 if it gets divided by 2.

Then, as the basic programming math, the mod works like multiplication/add/subtraction that if both operators/numbers are Integer, the result would be Integer. The mod operation is basically for obtaining the remainders from the division, i.e. 5 / 2 = 2, with remainders = 1, thus 5 % 2 = 1.

And, in the looping, the i is already a number, so pushing the Number(i) is equivalent with pushing i alone. If you just want to get the sum, the array is not necessary there and should be just removed. You can get the sum by accumulate it into the sum variable.

Thus, if you wish to get the sum of odd numbers in the range [2,50], it should be:

let letsCheck = () => {

    let sum = 0

    for(let i = 2; i <= 50; i  ) {
        if(i % 2 !== 0) {
            sum  = i;
        }           
    }
    
    console.log(sum);
}

letsCheck();

And if you wish to get the prime numbers from 0 to 50 excluding 2, it should be:

function isPrimeExclude2(num) {
  if(num <= 2) return false;
  for(let i=2; i*i <= num; i  ){
    if (num % i == 0) return false;
  }
  return true;
}

let letsCheck = () => {

    let sum = 0

    for(let i = 2; i <= 50; i  ) {
        if(isPrimeExclude2(i)) {
            sum = sum   i;
        }           
    }
    console.log(sum);
}



letsCheck();

  • Related