Calculating prime numbers in a range is another comparison in programming languages. In this article, we compared the speed of codes to find Prime Number functions in C++ and Python

Table of Contents

## 1. Introduction

Prime numbers are an interesting area to research. A **prime number**, it is also called **prime** shortly, is a natural number (a positive integer) greater than one that is not a product of two smaller natural numbers. If a number is not prime then it is called a **composed number**. There are several mathematical questions regarding prime numbers that are still unsolved. Finding them and relations and their effects on some other functions, graphics really interesting in mathematical phenomena.

In the programming world today, Python is very popular and easy to use. It makes popular because of supports from big companies (i.e. Google) and its successful libraries and frameworks on AI Technology. It is a great object-oriented, interpreted, and interactive programming language. It is often compared with C/C++, Delphi, Lisp, Tcl, Perl, Ruby, C#, Visual Basic, Visual Fox Pro, Scheme, or Java. Python has very clear syntax and it has some practical things. It has modules, classes, exceptions, very high-level dynamic data types, and dynamic typing. There are interfaces to many system calls and libraries, as well as to various windowing systems. New built-in modules are easily written in C or C++. Python is also usable as an extension language for other applications written in other languages that need easy-to-use. Python is free to use and more information can be found from their official web page https://www.python.org/

C and C++ are the fastest and one of the most powerful programming languages and it is easy to calculate prime numbers as fast as possible. In these tests we will use C++ Builder which has a great IDE, includes compilers for Win32, Win64, Android, and iOS. C++Builder has both CLANG Enhanced C/C++ Compiler and Embarcadero’s new Bcc C/C++ Compiler. It also features a modern, high-productivity RAD Studio IDE, debugger tools, and enterprise connectivity to accelerate cross-platform UI development. You can develop GUI based applications easily, as it comes with the award-winning VCL framework for high-performance native Windows apps and the powerful FireMonkey (FMX) framework for cross-platform UIs. There is a free C++ Builder Community Edition that can be used by students, beginners, and startups with limitations.

You can download the free C++ Builder Community Edition here: https://www.embarcadero.com/products/cbuilder/starter. Professional developers can use the Professional, Architect, or Enterprise versions of C++ Builder. Please visit https://www.embarcadero.com/products/cbuilder.

Python can be used inside Delphi projects and this prime number function is tested before in Delphi and in Python here https://www.youtube.com/watch?v=aCz5h96ObUM with Kiriakos Vlahos. Here, we were inspired by this video and we try to do the same tests on the same function in C++. Finding Prime Numbers in C++ is explained in detailed well in this **Easily Learn To Find Prime Numbers In Modern C++** post here.

Here, we compared the speed of Prime Number functions in C++ Builder 10.4 and Python 3.9.1.

## 2. System Description

*PC setup that we used in tests here is;*

OS: Windows 10 64 bit (Version 2004)

CPU: AMD Ryzen 7 1800X (3.6 Ghz)

RAM: 16 GB DDR4

GPU: Nvidia GTX 1080Ti

Drive: Samsung 960 Pro M.2 SSD*Software versions used:*

Python Programming Language Version 3.9.1

RAD Studio, C++ Builder Version 10.4

## 3. Counting Prime Numbers Example in Python

This is a Python example to find number of prime numbers in a given range.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
import time import math def is_prime(n): if n <= 1: return False q = math.floor(math.sqrt(n)) for i in range(2, q+1): if n % i == 0: return False return True def count_primes(max_n): res = 0 for i in range(2,max_n + 1): if is_prime(i): res += 1 return res max_N = 1000000 start = time.time() count = count_primes(max_N) end = time.time() print("Number of primes between 0 to {} = {}".format(max_N,count)) print("Elapsed time: {}".format(end-start)) |

## 4. Counting Prime Numbers Example in C++ Builder

This is a C++ Builder example to find number of prime numbers in a given range. Note that it runs with a Form which has a Button and a Memo box to display output.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
//--------------------------------------------------------------------------- #include <fmx.h> #pragma hdrstop #include "Unit1.h" //--------------------------------------------------------------------------- #pragma package(smart_init) #pragma resource "*.fmx" TForm1 *Form1; //--------------------------------------------------------------------------- __fastcall TForm1::TForm1(TComponent* Owner) : TForm(Owner) { } //--------------------------------------------------------------------------- #define max_n 1000000 //--------------------------------------------------------------------------- bool is_prime(unsigned int x) { if(x<=1) return(false); unsigned int q = floor(sqrt(x)); for(unsigned int i=2; i<=q; i++) { if((x%i)==0) return(false); } return(true); } //--------------------------------------------------------------------------- int count_primes(unsigned int maxN) { unsigned int res=0; for(int i=2; i<=maxN; i++) { if(is_prime(i)) res++; } return(res); } //--------------------------------------------------------------------------- void __fastcall TForm1::Button1Click(TObject *Sender) { unsigned int start,end,count; start = GetTickCount(); count = count_primes(max_n); end = GetTickCount(); Memo1->Lines->Add(L"Number of primes between "+IntToStr(max_n)+L"= "+UIntToStr(count) ) ; Memo1->Lines->Add(L"Elapsed time:"+UIntToStr(end-start)+L" ms"); } //--------------------------------------------------------------------------- |

## 5. Results in Python and C++ Builder

This test below is about **Python 3.7.9 64bits** comes with latest Spyder

This test below is done with the latest **Python 3.9.1 32 bits **version

This test below is done with the latest **Python 3.9.1 64 bits** version,

In these counting prime numbers tests we also found that Python 3.9.1 version looks faster than 3.7.9 version which comes with current Spyder editor. It is obvious that 64bits test doubles 32bits test in speed.

We also tested counting prime numbers with same procedures in C++ Builder with system information in our post here before. Here are some of results.

As shown above we try to do same as same code as possible given in Kiriakos Vlahos’s video and we tested same cases 5 times on both C++ Builder and Python. Let’s see these results in tables.

These tables above show that calculating the number of prime numbers in 32bits takes 0.494 seconds in C++ Builder (including with Modern FMX GUIs) and Python 3.9.1 is doing the same operation in 8.770 seconds In this test, in comparison C++ Builder is **17.8 times faster in 32bits** and calculating number of prime numbers in 64bits takes 0.350 seconds in C++ Builder (including with Modern FMX GUIs) and Python 3.9.1 is doing the same operation in 3.298 seconds that means C++ Builder is **9.4 times faster in 64bits**. Note that we made the same tests before with **GNUC/C++** on the same system and we post it here and here with **VSCode** before, and we did the same tests on the latest Dev-C++ and results can be found here. All C++ tests are runs with about the same scores in different compilers on the same system given above.

We also found that Python 3.7.9 comes with Spyder is slower than 3.9.1 in our tests. Here is a table in comparison with C++ Builder below.

## 6. Conclusion

In conclusion, on the same PC System, our tests show that C++ ( C++ Builder BCC & CLANG, GNU C/C++, Dev C++, VS Code) is about 9.4 times faster than Python on counting prime numbers in 64 bits and about 17.8 times faster in 32 bits. The calculating number of prime numbers is good to use some basic logical operations and mathematical functions. The procedure includes logical if() clauses, for() loops, some mathematical procedures (floor, sqrt etc.), that show C++ is very fast in mathematical operations. These kinds of tests can be done in different operations to compare languages.

Note that all tests were done on a single core/thread test. C++ Builder is capable to do Threads and easy to use Parallel algorithms for multi-thread operations. It shows that threaded tests are much faster, depends on the number of cores/threads.

Actually, results were obvious because of Python is an interpreted programming language with some benefits while C/C++ is a non-interpreted (compiled) programing language. Here C++ proofs that still it is very fast to do mathematical operations in comparison with Python. These kinds of tests can be done on many mathematical operations and on other codes. Speed changes may improve analyzes and other operations (i.e face detection, image processing, or other AI technologies). If your applications are built with C++ they will have faster operations in each task. On the other side, Python has some advantages in coding, easy to code, well on AI technologies with some TensorFlow, Keras frameworks. Users should define their priorities before coding an application and they should choose their programming language for their projects.

Please keep following our next posts on these tests.