Today I am going to talk about calculating primes.
The Algorithm that I am going to introduce is a brute force method for calculating prime numbers.
It is great for comparing the computing power of two machines by looking at overall execution times.
This routine consists in dividing n by each integer m which is greater than 1 and less than or equal
to the square root of n. If the result of any of these divisions is an integer, then n is not a prime;
otherwise, it is a prime.
I am going to use both the “Application Logging” and “Write Text File” classes that were discussed earlier to solve this problem.
I always like to create a high level program algorithm before starting any coding. I usually write it in psuedo code so that is program like in nature.
Calculating Primes Algorithm:
Get script arguement (N-max prospect)
Record start time
Write arguement N to log file
Write 2 & 3 as first two primes to CSV result file
Set found counter = 2
For M = 4 to N
For O = 2 to SQRT(M)
If M modulus O = zero, then non prime, exit for
Otherwise, write prime number to CSV result file
Increment found counter
Write number of primes found to log file
Record end time
Calculate & write time elapsed to Log file
The table below has the Visual Basic (VB) Scripts used in the solution and the output files. I ran the program to calculate all the prime numbers less than or equal to 2.5 Million. The program executed in 91 seconds on a Dell i5 Laptop running Windows 7 – 32 bit operating system and found 183,072 prime numbers.
|mod-write-text-file.vbs||Write Text File Class|
|mod-app-logging.vbs||Application Logging Class|
|prg-calc-primes-v1.vbs||Calculate Primes Program|
|primes.cmd||Primes Batch File|
|prg-calc-primes-v1.log||Primes Log File|
|primes||Primes Result File|
This is a screen shot of the calculating primes VB Script excuting in a MS DOS command shell.
As you can see, the second time I ran the program it took 95 seconds. Just to show you that background processes like email, word, and etc. can have sligth performance impacts of heavy computational programs.