"Will code for travel"

Search technical info
How to generate small prime number list using Python?
Written: 2019-10-11 07:56:04 Last update: 2019-11-04 22:34:51

Previously, I have use JavaScript to generate small prime numbers online, the JS code will be run in client-side using whatever browser and the speed will be depending on the user machine spec.

This article will using python code to generate small prime number list, because python can not be executed in client-side inside browser like JavaScript, so I have to deploy it to a server and I have selected pythonanywhere.com which has a free hosting for python, I have have deployed it and to see the working action please see Python small prime numbers generators, I found this free python server's speed is much slower compare to my own local machine, but for a free service it is good enough to make a working prototype or just for sharing python app to others.

I have compared the speed using the JavaScript engine and the python, the implementation logic is quite similar, in my own testing to generate all small prime number under 1 million, the JavaScript running in Chrome browser takes 0.046 seconds and the python3 (in command line) implementation takes 0.55 seconds, it is strange to see the JavaScript is so much faster even though it runs on Chrome.

There are a couple of reasons I want to do this, firstly to see how easy to use python to generate small prime numbers and secondly to use pythonanywhere.com free service and to see its computing speed using Django framework.

This python code is only the main logic function, there are other python code to show the result in UI using Django framework but it is not shown here because it is not important for the test.

# limiter, to avoid accidentally use very large number which will take a long time
MAX_LIMIT = 10 ** 6

def generateSmallPrimeNumbers(n):
    
    # handle small value
    if 2 > n:
        return []
    elif 2 == n:
        return [2]
    elif 3 == n:
        return [2,3]
    elif n > MAX_LIMIT:
        #max limit
        n = MAX_LIMIT
    
    method = 2
    if method == 1:
        return _generateSmallPrimes_1_brute(n)
    else:
        return _generateSmallPrimes_2_limiter(n)

def _generateSmallPrimes_1_brute(n):
  # init prime list, init with first and second prime (2 and 3)
  primes = [2,3] 

  # from 5 to n, step=2, eg: 5,7,9,11,13,15,etc.
  
  # include n
  limit = n + 1
  for v in range(5, limit, 2):

      sqrt_limit = int(v ** 0.5) + 1

      # do small-prime divisions
      # starting from second index (3) to current total primes
      # NOTE: skip division by 2 because no even value

      isPrime = True
      for j in range(1, len(primes)):
          prime = primes[j]
          if prime > sqrt_limit:
              break
          if v % prime == 0:
              isPrime = False
              break
      
      if isPrime:
          primes.append(v)

  return primes 

def _generateSmallPrimes_2_limiter(n):
  # init prime list, init with first and second prime (2 and 3)
  primes = [2,3]

  # init limiter variables
  primeArrayIndexLimit = 1
  maxValueWithLimit = primes[primeArrayIndexLimit] ** 2

  # next number to check
  v = 5

  # loop until reached the final value
  while n >= v:

      # avoid overshoot 
      if maxValueWithLimit > n:
          maxValueWithLimit = n + 1 # + 1 to include 'n'

      # get value to check, only for ODD values, eg: 5,7,9,11,13,15,17,etc.
      for v in range(v, maxValueWithLimit, 2):

          isPrime = True

          # divide by existing small primes, skip first prime (because v always ODD !!, primes[0] == 2)
          for i in range(1, primeArrayIndexLimit):
              if v % primes[i] == 0:
                  isPrime = False
                  break

          if isPrime:
              primes.append(v)
      
      # increase v to avoid double check same v
      v += 2

      # update limiter
      primeArrayIndexLimit += 1
      maxValueWithLimit = primes[primeArrayIndexLimit] ** 2

  return primes

######## TESTING generate prime numbers with small value ########## 

if __name__ == '__main__':        
  import time

  n = 113 #1000000

  time_start = time.time()
  primes = generateSmallPrimeNumbers(n)
  time_end = time.time()

  print('generate prime up to ', n, 'total primes: ', len(primes))
  print('elapsed time ', format(time_end - time_start, '.3f'), ' seconds')
  print(primes)

This is the steps I use to create a free python web app in pythonanywhere.com, below is optional to read, it is only for documentation.

  1. Create Django web app in local machine and fully develop this python (with Django framework) project.
  2. Push the code from my local machine to github
  3. Create a free account in pythonanywhere.com and login
  4. Open bash console, setup python version and install Django framework
  5. Create a new virtual environment and clone the full code from github.
  6. Adjust the WSGI configuration file, restart and see the working python web app.

Pythonanywhere.com is a great free service to host python code, it has full feature python hosting with an online file editor, it allows developers to use tablet, ipad or smartphone to do python coding without computer, it is very easy to setup Django framework too, for starting point just follow Django tutorial.

First we need to create a new web app, it will also create a new subdomain, in my case it is quickwork.pythonanywhere.com, select python web framework, the documentation stated that we need to select 'Manual configuration' (not Django), then select python version, I selected python 3.6 because I am using Ubuntu 18.04 LTS which current latest stable version of python is 3.6.8, I can select python 3.7 and is already released for Ubuntu but I want to avoid it because it may have stability issue for Ubuntu 18.04's terminal system and other Ubuntu app, next we need to create virtual environment in bash console (command line terminal in browser) using virtual environment wrapper to make it easy, I named my virtual environment as 'myenv' (we can name the virtual environment whatever we want)

$ mkvirtualenv --python=python3.6 myenv

Install Django framework from inside the created virtual environment, the bash console will automatically make it active and immediately go inside the virtual environment after created.

(myenv) $ pip install django

Clone the full web app code from my PRIVATE GitHub using the same console, go to home directory ($ cd ~), please remember do not clone the code into virtual environment directory.

(myenv) $ git clone https://github.com/HMaxF/python_generate_small_primes

Go back to the UI console and set the newly created virtual environment, in 'Virtualenv' menu type-in 'myenv', at this stage we have completed our web app, at first when I open quickwork.pythonanywhere.com then I can see the default 'Hello World' message, to change the content to my Django web app I need to edit the 'WSGI configuration file', in my case the file path is '/var/www/quickwork_pythonanywhere_com_wsgi.py', click it and use the file editor to edit it.

# +++++++++++ DJANGO +++++++++++
# To use your own django app use code like this:
import os
import sys

## assuming your django settings file is at '/home/quickwork/python_generate_small_primes/quickwork/settings.py'
## and your manage.py is is at '/home/quickwork/python_generate_small_primes/manage.py'
path = '/home/quickwork/python_generate_small_primes/quickwork'
if path not in sys.path:
    sys.path.append(path)

os.environ['DJANGO_SETTINGS_MODULE'] = 'quickwork.settings'

# then:
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()

Please note that every time we change the WSGI configuration file, then we must reload (restart the service) to see the new updated content.

At first I have to read many documents and watched some youtube videos to understand how to use pythonanywhere free service, it was a little confusing and require some time to learn, but after I've completed it I think it is not so difficult, pythonanywhere make setting and file editing as easy as it could, I hope this article can help other who want to use pythonanywhere.com for to share their python web app.

Last reminder if using free account in pythonanywhere.com, our project will have 3 months cycle expiration date, to avoid our project expired and closed we need to login and go to 'Web' tab and click the 'Run until 3 months from today' button at least once every 3 months.

Search more info