E
E
Evgeniy2021-07-06 17:56:21
JavaScript
Evgeniy, 2021-07-06 17:56:21

How to understand this function?

Good afternoon, please explain on your fingers what is happening here?
confused
The function determines whether a number is prime or not

A prime number is a number that has 2 divisors, itself and one

spoiler

const isPrime = (number) => {
  if (number < 2) {
    return false;
  }
  
  for ( let i = 2; i <= number / 2; i++) {
    if (number % i === 0) {
      return false;
    }
  }
  
  return true;
}

document.write(isPrime(7))



For example, with the number 7
How are the calculations going in the cycle?

If 1 is always added to i after each loop, but the loop is limited to 3.5 in this case, how does the function understand that 7 is a prime number?
After all, we will not reach 7 in the cycle.
And the function does not check only division by 2, for example, 9 is divisible by 3, and is not a prime number.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2021-07-06
@Zheleznov

With 7, they check whether it is divisible by 2 and by 3 - it is not divisible by either, which means that it is simple.
Why half. Because the second factor cannot be less than 2, only greater than or equal to.
The meaning of enumeration is to catch that, here, aha! - divisible by this number! — means, not simple and further it is possible not to check.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question