Calculating Prime Numbers Algorithm in Python

Another common puzzle used to develop your coding skills is to use your chosen language to find all of the prime numbers between any given range. This range would usually start from 2 since the rules of being a prime number is that the number should only be divisible by one and itself. The number 100 is a typical arbitrary figure chosen as this was commonly cited during schooling years.

As a general approach to the problem at hand, this involves looping over each of the numbers in the range (in this example, from 2 to 100). Within that loop, loop over each of the numbers (between 2 and itself) to check if the number being tested is divisible by any other number between 2 and itself. This is done using modulo arithmetic.

If the operation finds any instance where there is a remainder, then the number is not considered a prime number. If all of the numbers within the range have been tested and there are no numbers that had a remainder component, then it is considered to be a prime number and it is appended to the prime numbers list within the master function.

Here is an implementation in Python:

def is_prime(number):
    """ Determines whether given number is prime or not """
    for factor in range(2, number):
        if number % factor == 0:
            return False
        return True

prime_numbers = []
def get_prime_numbers(max_num):
    """ Builds list of prime numbers up to a maximum of max_num """
    for tested_num in range(2, max_num):
        if is_prime(tested_num):
            prime_numbers.append(tested_num)
    return prime_numbers


if __name__ == '__main__':
    prime_numbers = get_prime_numbers(100)
    print(prime_numbers)

 

Here is the same implementation written in JavaScript:

// List prime numbers between 2 and 100

primeNumbers = []

function isPrime(number) {
   ` Determines whether given number is prime or not `
  for (let factor = 2; factor < number; factor++){
       if(number % factor == 0){
          return false;
       }
   }
   return true;
}

function getPrimeNumbers(maxNum) {
  ` Builds list of prime numbers up to a maximum of maxNum `
  for(let testedNum = 2; testedNum <= maxNum; testedNum++) {
      if(isPrime(testedNum)){
        primeNumbers.push(testedNum)
        console.log(primeNumbers);
    }
  }
}

primeNumbers = getPrimeNumbers(100);