In every year, π day is celebrated on March 14th (3.14).

π is a super star in mathematics. It is mysterious and people keep exploring it. It is proven that this constant has no end hence it is irrational, that means it cannot be represented as a fraction. π is bigger, as big as the whole universe. In deed π is not the only irrational number we got. But π attracted many and we keep loving it.

Even though there is no known benefit of calculating the value of π people insist of doing it. For many engineering applications, having value of π for 3 or 4 decimal places would be sufficient. Other sophisticated scientific advanced might need much more accuracy but I am pretty sure, it is enough to know first 100 digits of π. But today, humans have calculated 22,459,157,718,361 digits[1] of π.

There are quite many activities are organized for the π day worldwide other than enjoying delicious pies. One of the interested things is ,contests on memorizing decimal places of π. The current world record is 70030 digits[2].

To celebrate the π day I have calculated π for 7 decimal places using **Gregory and Leibniz series**. It is one of the most primitive ways of calculating π though.

[1] https://en.wikipedia.org/wiki/Chronology_of_computation_of_%CF%80

[2] http://www.pi-world-ranking-list.com/index.php?page=lists&category=pi

PS: Following script gives 7 decimal digits of π.

ans = 0 for k in range (1,100000000): temp = ((-1)**(k+1)/(2*k-1)) ans = ans + (temp*4) print (ans)

]]>

Even though the direct access is restricted, it is possible to access these services through Proxy Servers and VPN (Virtual Private Network) applications. There are some false information, being circulated that the use of either social media services or VPN applications are illegal. There is no ground for such misleading information.

No action can be taken against anyone as long as the services are used in the right manner. Use indirect methods to access these services and use them but do not get involved in spreading racism.

At this moment, it is reported that access of some VPN services are also restricted. But there are plenty of VPN services out there which can be used for the purpose.

Do raise your voice against this restriction !!

Do use social media services responsibly !!

]]>Euler’s Totient Function, also known as Phi Function, Prime Counting Function or is used to count number of co-primes prior to a given integer. In other words, the function outputs number of co-primes which are less than the given number.

Co-primes are integers which does not share any common factors. For an example even though 8 is not a prime, it is a co-prime of 15. Because 8 = 2*2*2 and 15 = 2*5, therefore it can be seen that 8 or 15 does not share a common factor.

If a given integer is a prime, obviously all the integers less than the given number are co-primes to the given prime. Therefore, it is easy to calculate if n is a prime. When *n* is a prime; in

When* n* is not a prime, can be calculated as follow:

First, the number should be broken into prime factors, then after it is a matter of applying the following equation:

*(prime factors of n)*

This is another interesting property of which can be used to compute .

When, p and q are prime numbers:

as a fact, if p and q are prime numbers then,

Calculating :

Using the above equation:

n = 24, m = 2 and primes are 2, 3:

Will check if the answer is correct, using the besic definition:

Following are all the integers less than 24, starting from 1

1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23

Remove co-prime of 24:

**1**, ~~2, 3, 4~~, **5**, ~~6~~, **7**, ~~8, 9, 10~~, **11**, ~~12~~, **13**, ~~14, 15, 16~~, **17**, ~~18~~, **19**, ~~20, 21, 22~~, **23**

Remaining number count is 8, therefore both answers match.

It is possible to use the above equation to calculate in Python. However, it is easier to use the definition of prime counting rather than using the equation.

The algorithm would be as follow:

- needs to be calculated.
- Start from
*k*= 2,*counter*is 0. - Check if the selected integer (
*k*) is a co-prime to*n*. - If it is a co-prime increase the counter.

To check if *k* is a co-prime to *n*, GCD operation can be used.

def calculate_phi(n): phi_n = 1 count = 0 i = 2 while (i<n): r = gcd_euc(n, i) i = i + 1 if(r==1): phi_n = phi_n + 1 return phi_n

Above mentioned methods can be used to calculate of a given integer. Results of the phi function is often applied in cryptography.

]]>For an example, like calculating; (which is multiplying 3, four times), this is pretty straight forward:

In order to get the answer 3 rounds of calculations are required.

In that same manner, to calculate , 12 rounds of multiplication rounds are required. Nevertheless it is possible to use the following method and reduce number of required rounds.

Above is a short cut method to obtain the answer, however things might go weird when the exponent is really large, for example something like or .

Even using the shortcut method seems quite cumbersome but better than the first method.

However, in such situations * Square and Multiply method *comes handy. Even in the second method, we have applied Square and Multiply operation to get the answer. Using this algorithm make it easier to apply the logic behind, especially when it needs to be implemented as a computer program.

Taking back the earlier example, check the operations carried out:

**(Square)**

**(Square)**

*(Square) *

*(Multiply) *

*(Multiply) *

what if the above is arranged as follow:

*(Square) *

*(Multiply) *

**(Square)**

**(Square)**

**(Multiply)**

Even though that there is no much improvement in computational rounds, the second approach aligns with the * Square and Multiple method*. So as you might already have understood, the

Following steps needs to be carried out :

- Get the binary representation of the exponent.
- Bits are read from left to right (MSB first) and it should start with a 1.
- Starting
*value*= - Start scanning bits from the left.
- As mentioned above the first bit must be 1.
- If scanned bit is 1 then, square the
*value*and then multiply by - If scanneed bit is 0 then, square the
*value*. - Repeat this for all the bits.

As an example, can be taken. Binary representation of 13 is:

Since the first bit is 1, initially the value is squared and multiplied. Then next bit is taken, it is 1, therefore the value is square and multiplied again. Then the third bit is 0, therefore the value is only squared. Final bit is 1, the value needs to be squared and multiplied. Pretty easy right !

Time to check this method for a larger exponent. Lets take following :

Steps:

*(Square )*

*(Multiply)*

*(Square )*

*(Multiply)*

*(Square )*

*(Square )*

*(Multiply)*

*(Square )*

*(Square )*

*(Square )*

*(Multiply)*

Following is the python code:

string bin(int num)

The above function takes an integer as the argument and then return the binary equivalent as a string. It starts with **0b** prefix. Therefore it is required to consider [2:] of the string. As the first bit is always 1, the final output of the first step is always equal to x. That is the reason for starting the for loop from 3.

def exp_func(x, y): exp = bin(y) value = x for i in range(3, len(exp)): value = value * value if(exp[i:i+1]=='1'): value = value*x return value

Square and Multiply algorithm is a very useful algorithm which can be used to calculate values of integers having really large exponents. The number of calculation rounds is relatively less compared to the brute force method.

]]>When two numbers are divided, it produces two things. One is termed as the **Quotient** and the other is termed as the **Remainder**. Based on the application, more focus could be given either to the Quotient or to the Remainder. Today, will focus on the Remainder and find how to deduce the Remainder when a large number is divide by a comparatively small number without doing extensive calculations.

According to the Euclidean division, this can be written as follow:

let ** x** – numerator,

Using the above equation, will try to find the remainder of 27 / 12.

It is possible to try applying *k* = 1 ; *k* = 2 and then calculate *r*, at *k* = 2 we get the answer which is *r* = 3 . This algorithm is promising, however when the numerator (*x*) is relatively a large number, more computation is required.

For an example, try to find the remainder of

Assuming this calculation is done by hand, as the numerator is a large number it is not possible to compute the remainder using the above algorithm, of course it is possible but it might take lot of computational steps and time. Therefore another approach is required.

To understand easily, will consider following generalize form;

- Break the numerator (
*x*) into two numbers where*y*needs to be a factor of one of the numbers. Let numbers are*a*and*b*, then a = k * y and*x = a + b* - When there are some combinations available for
*a*and*b*try to obtain the minimum value for*b*which satisfies the requirement mentioned in step 1. Obtaining*b = 1*is the ideal, if possible. - Once above steps are concluded, the equation reduces to , further it can be deduce to
- Once it is reduced, the remainder can be easily obtained by solving
- In a scenario where
*b = 1*, then the answer is 1 as is always 1.

Getting back to the example mentioned above,

- 25 can be broken into 1 and 24, a = 24 and b = 1, 12 become a factor of a therefore the combination satisfies the requirement.
- Then solve , which is equal to 1.

Results can be verified with the following python code as well:

<pre>print('Remainder - ',(25**243)%12)</pre>

In such scenarios, where *b* is not possible to take as 1, it is required to solve the equation numerically. But even though the numerator is reduced, still it requires more computational effort.

When *b* is not equal to 1, following method can be used. It follows patterns recognition and then deduce the answer.

To understand the concept behind, will take a slightly different version of the above example, assume that it is required to calculate the remainder of

At this time, as the numerator is 26, it is not possible to break into two numbers in which b = 1. When a = 12, b = 2. Therefore following algorithm needs to be used to deduce the remainder from the reduced equation.

The reduced equation for is

Then take the reduced equation as where p = 243

The next part is identify the pattern by applying p = 1, p = 2, p = 3 ……… This needs to be done until a pattern can be recognized.

at p = 1 remainder is 2

at p = 2 remainder is 4

at p = 3 remainder is 8

at p = 4 remainder is 4

at p = 5 remainder is 8

at p = 6 remainder is 4

A pattern, now can be recognized. It seems when p is odd remainder is 8 and when p is even the remainder is 4 for all p when p>1. As we are looking for the remainder when p = 243 which is an odd number, as a result the remainder should be 8.

Verify the answer with the following python script.

print('Remainder - ',(26**243)%12)

Recognizing the pattern is quite cumbersome but it is always easier than working out the whole equation.

Finally, below is the mathematical proof for the above algorithm:

Let : where y ≠ 0 and *x* and *y* are positive real integers.

In Euclidean division, *x = k * y + r* ———————(1)

applying (1) ,

Term (k*y+r), can be treated as binomial expansion as *a = k*y* and *b = r*

———–(2)

In equation no. 2, it can be noticed that each term has a factor of *a* except the last term, which is , that means each term is divisible with no reminder except the last term. Therefore that is the only term which generates a remainder. Calculating the remainder for the last term gives the remainder of the whole equation, that is why it is possible to reduce the original equation to:

When calculating prime numbers, it is often required to check if a given number has factors. One of the efficient ways is to divide given numbers and check if there is a remainder. For such operations this algorithm can be used specially when the numerator and the denominator are relatively large (in exponent format). Furthermore, if it is possible to break numbers into *a* and *b* (step 1 in Algorithm) such a way that *b = 1*, at a glance the remainder can be obtained. Therefore this is a faster technique that can be mastered to calculate the remainder manually and also can be implemented in computer aided calculations as well.

For an example, GCD of 20 and 12 is 4. GCD of 18 and 12 is 6. Further, since primes dont have factors (other than 1 and the prime itself) the GCD of any two prime numbers is 1. There is no common factors for 20 and 11, therefore GCD for 20 and 11 is also 1. GCD is not limited to 2 integers, it can be for more than two. For an example, GCD of 30,60 and 90 is 30.

In order to calculate GCD of two numbers following algorithms can be used:

function cal_gcd(x, y)Input: Let x and y are two integers d = min(x,y) while (True) if(x mod d is zero) and (y mod d is zero) return d else d = d - 1

Above algorithm can be used to calculate GCD of two numbers. With a slight modification, the code snippet can be changed so that it calculate GCD for more than two integers.

function cal_gcd_(list)Input: list of integers d = min (list) while (True) if remainder = 0 for all integers in the list when divided by d d = d -1 else return d

These two algorithms perform better, however once the integers are quite large, these algorithms are not efficient. For large integers, Euclid’s algorithm can be used. Python implementation of the above method mentioned below.

**Python Code:**

def gcd_gen_list(list_num): d = min(list_num) cal = True while(cal): counter = len(list_num) for i in range(0, len(list_num)): if (list_num[i] % d != 0) : d -= 1 break else: counter -= 1 if((d==1) or (counter == 0)): return d

This is a pretty interesting method. This method is based on the divisibility concept.

Let, *x* is divided by y, so that the result is k and remainder is r. In such a case it can be expressed as;

*x = k . y + r*

Plus this method uses the following theorem.

GCD of integer *x* and *y* is equal to GCD of integer *y* and *r*.

Repeating this concept till remainder reaches zero*.*

**Pseudocode algorithm:**

function gcd_eucInput: Let x and y are integers calculate r (r = x mod y) while (r is not 0) calculate r (r = y mod r) return r

This method is pretty straight forward and very fast when compared to the method mentioned above for large integers.

**Python code:**

def gcd_euc(x, y): r = x%y while (r != 0): x = y y = r r = x%y return int(y)

This is another algorithm which can be used to compute GCD of two integers. It uses subtraction of numbers to calculate the GCD.

**Pseudocode algorithm:**

function gcd_dijkInput: Let x and y are integers while (x != y) If x > y Then x = x - y Else: y = y - x return x

**Python code:**

def gcd_dijk(x, y): while(x!=y): if(x>y): x = x-y else: y = y-x return x

The Binary method also known as Stein’s algorithm is also one of the algorithms to compute GCD. It is quite more complex than Dijkstras Algorithm. However unlike

Dijkstras Algorithm it uses division by 2, therefore it is possible to use bit operations.

**Pseudocode algorithm:**

function gcd_binaryInput: Let x and y are integers while (x != y) factor = 1 If x is 0 Then return factor * y If y is 0 Then return factor * x If x is even AND y is even Then factor = factor * 2 x = x / 2 y = y / 2 If x is even AND y is not even Then x = x / 2 If x is not even and y is even Then y = y / 2 If x is not even AND y is not even Then If x > y Then x = (x - y ) /2 Else y = (y - x) / 2 return factor * x

**Python code:**

Python implementation is provided below. Note that bit-wise operator >> and << have been used instead of multiplication of 2 or division by 2.

def gcd_binary(x, y): factor = 1 while(x!=y): if (x==0 or y==0): return factor*(x+y) if (is_even(x) == False and is_even(y) == False): if(x>y): x = (x-y) >> 1 continue else: y = (y-x) >> 1 continue if(is_even(x) and is_even(y)): x = x >> 1 y = y >> 1 factor = factor << 1 continue if(is_even(x)==True and is_even(y)==False): x = x >> 1 continue else: y = y >> 1 continue return factor * x def is_even(x): y = x >>1 if(y<<1==x): return True else: return False

All methods other than the General Method can be used to calculate GCD for 2 integers at once. In order to calculate GCD for more than two integers, it is possible to calculate GCD for pairs and then select the lowest GCD for all the pairs.

**Python code:**

def gcd_list(numList): numListSize = len(numList) GCDList = list() for i in range(0, numListSize): for j in range(0, numListSize): if(i!=j): ans = gcd_binary(numList[i], numList[j]) GCDList.append(ans) return min(GCDList)

All methods can be found in bmaths library under bmaths_gcd.py

**bmaths library is released under GNU General Public License v3.0**

https://github.com/bckurera/elec_res_parse

The direct connection socket to the site has been removed. Therefore follow below steps unless you want to add your own socket to read the site (check my earlier post on Python Socket programming):

- Open the relevant result page and save it in your local PC.
- Rename the file name to 98.html (or change the file name in the script)
- Execute the script.

In this approach, python library **socket** is used. It is a part of the standard Python library, hence no manual installation is required.

This is a simple server which keeps listening to an incoming traffic from a client and then respond.

#!/usr/bin/python import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = '127.0.0.1' PORT = 30303 BUFFER_SIZE = 2014 s.bind((HOST, PORT)) s.listen(5) while True: print ('server running --') conn, addr = s.accept() data = conn.recv(BUFFER_SIZE) print ('Got connection from ', data, '-', addr) conn.send(b'Thank you for connecting') conn.close()

Note how the socket object has been initialized and then HOST address and the PORT have been defined. **bind( )** method reserves the port for the host. **accept( )** method accepts the incoming connection and then output another instance of the socket object as ** conn **and the

When sending data using **send( )** method, the content should be a byte-like object. No string objects can be used. That is why * b* literal is used. Or

Following is the code snippet for the client.

Code is almost as same as the server code other than not having a loop to listen to the incoming traffic. It simply send some data to the server and then receives the output from the server.

#!/usr/bin/python import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = '127.0.0.1' PORT = 30303 s.connect((HOST, PORT)) s.send(b'username:user') data = s.recv(1024) print (data) s.close ()

The server code needs to be executed first and then the client code.

However, since there is no threads in the server code, only 1 connection can be established with the server at a time.

It is possible to use the client code to contact a web server (or any other service) and request a web page. Or even contact a FTP service. The send request needs to be modified according to the protocol.

Following is a simple example on getting a web page using the client code. Localhost is used in the code however the HOST can be replaced with any URL which supports HTTP.

#!/usr/bin/python import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) HOST = '127.0.0.1' PORT = 80 s.connect((HOST, PORT)) s.send(b'GET /test/index.php HTTP/1.1\n' b'Host: 127.0.0.1\n' b'Connection: keep-alive\n' b'Upgrade-Insecure-Requests: 1\n' b'\r\n') data = s.recv(1024) print (data) s.close ()

Notice that only the send method has been changed to facilitate **HTTP** protocol. The output is a plain-text including header and body content. Further processing is required.

For HTTP protocol, httplib module can be used too. However it is not a part of the standard Python library and it is required to get it installed manually. In the same manner, few non-standard libraries are available for **FTP (ftplib)**, **SMTP (smtplib)**, **POP3 (poplib)** protocols.

This is a simple introduction on socket programming in Python. According to your requirement the code needs to be modified. The intention was to demonstrate how Python can be used for the above mentioned purpose.

]]>The video sampling is measured by the frame rate, for general use it is frames fer second or for high speed motions capturing, frames per millisecond. That means number of frames displayed per time unit. 24 fps (frames per second) is one of the most common frame rate for films. That means 24 frames will be captured/ projected in a second, 24 images in a second.

Following video frame rates with 1/1000 subdivisions are considered when deriving this new unit, flick.

**24 fps, 25 fps, 30 fps, 48 fps, 50 fps, 60 fps, 90 fps, 100 fps, 120 fps**

when converted to numbers, considering 1/1000 sub divisons:

**24 000, 25 000, 30 000, 48 000, 50 000, 60 000, 90 000, 100 000, 120 000**

Then not only video, audio is also sampled. In the following manner.

8 kHz, 16 kHz, 22.05 kHz, 24 kHz, 32 kHz, 44.1 kHz, 48 kHz, 88.2 kHz, 96 kHz, 192 kHz

When converted into numbers.

8 000, 16 000, 22 050, 24 000, 32 000, 44 100, 48 000, 88 200, 96 000, 192 000

The new time unit is chosen in a such a way that the above rates can be represented with no fractions, the result is a full integer value. It can be noticed that it is inevitable getting fractions even a nano-second is used as the smallest time unit.

If the new value is * f* then following equation should be the new representation:

**flick value representation = f / (video or audio sample rate)**

To find out** f**, Least Common Multiple (LCM) should be calculated in following numbers.

**24 000, 25 000, 30 000, 48 000, 50 000, 60 000, 90 000, 100 000, 120 000, 8 000, 16 000, 22 050, 24 000, 32 000, 44 100, 48 000, 88 200, 96 000, 192 000**

However, it can be noticed at once, that the number list can be reduced before applying LCM. Because 48 is a multiple of 24, 90 is multiple of 30, therefore the list reduces as follow :(eliminate smaller number which is factor of a larger number)

**90 000, 100 000, 120 000, 88 200, 192 000**

then after, it is possible to prime factorize above numbers: (you may use the following calculator[3])

90 000 = 2 x 2 x 2 x 2 x 3 x 3 x 5 x 5 x 5 x 5 = 2^4 x 3^2 x 5^4 100 000 = 2 x 2 x 2 x 2 x 2 x 5 x 5 x 5 x 5 x 5 = 2^5 x(5^5)120 000 = 2 x 2 x 2 x 3 x 5 = 2^3 x 3 x 5 88 200 = 2 x 2 x 2 x 3 x 3 x 5 x 5 x 7 x 7 = 2^3 x(3^2)x 5^2 x(7^2)192 000 = 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 2 x 3 x 5 x 5 x 5 =(2^9)x 3 x 5^3

According to the method, the next step is to extract higher power primes.

* f *= 2^9 x 3^2 x 5^5 x 7^2

If a flick is defined as one, 705 600 000th of a second, all above mentioned rates can be divided without getting any fractions as the result. The result is an integer always.

Further, a flick is nearly 1.4 times larger than a nano-second.

* f* = (1/ 705 600 000) second

A video with a common rates such as 24 fps (video sampling rate) and 44.1 kHz (audio sampling rate) can now be expressed as 29 400 000 flicks (video rate) and 16 000 flicks (audio rate). Or even it can be denoted 29.4 mega-flicks and 16 kilo-flicks. (could not find any reference for using mega or kilo with flicks anyway)

That is how, the new unit, flick enables conversion of rates without any lose of information of the video sampling or the audio sampling. That is why it becomes a cool representation. C++ implementation can be found in GitHub[2]

[1] http://www.bbc.com/news/technology-42787529

[2] https://github.com/OculusVR/Flicks

[3] https://www.calculatorsoup.com/calculators/math/prime-factors.php

Free 2 tickets, wow ! I could not wait till I finished reading the message. Because it is all about 2 free tickets from the national carrier. This is unbelievable. So I did check the URL, first it seems that the URL is as same as the official URL of the carrier which is srilanka.com. Everything seems pretty cool. So I read it again and checked the URL. Then it flipped. The URL is srilank**á**n.com , notice the letter **á**, instead of **a**.

If you visit the website, it looks as follow. It looks real, almost real, even the logo is also there.

You need to provide some answers, basically YES and NO for 4 questions and congratulations, you secured 2 free tickets. In the next screen, you need to send this to your WhatsApp contacts. Then after you can claim your 2 free tickets.

This URL wont work for desktop browsers, it keeps saying that the offer is not valid for the region while it gets directed to the following URL http://promopage.life/tick/g.php. The reason is pretty simple because it targets the mobile users as it needs WhatsApp to spread the news.

This is not a very smart phishing attack though it is mediocre. The attacker has matched the URL, it is so hard to notice the difference. The web site looks real too. However the Facebook section is not working at all. The connection is not secured (https). This is why you need to check for **https** always, make it a habit.

Although the offer of 2 free tickets raises your eyebrows, at the same time, it rings a bell. Because it is hard to believe that an airline is just throwing 2 free tickets for a simple survey like this. It would feel real, if it was like 50% for tickets or somewhat.

Finally, to avoid such malicious hoax, make sure you check the URL before you click it. Then look for **https**, a secure connection. Think before you share anything, specially when you are asked to share something via facebook, WhatsApp, Viber and etc. Last not the least, make sure you use your common sense too.

**EDIT** : Having https doesnt prove the authenticity. But not having https should ring a bell. So dont get confused. Checking for https (SSL EV) would be good test.

Did you get the same message? If so what did you do?

]]>