A code to find Primes - Sieve of Eratoshenes

To some extent the beauty of number theory seems to be related to the contradiction between the simplicity of the integers and the complicated structure of the primes, their building blocks. This has always attracted people.

A. Knauf from "Number theory, dynamical systems and statistical mechanics" 

This quote is indeed true. If you just think about the simplicity of integers and complexity of primes, it's really horrifying. It's almost like how easy and intuitive it is to analyse big "classical objects" but extremely un-intuitive to discuss about "quatum objects".

Today's blog will be a bit special. Today we will discuss about a simple algorithm which is one of the most easiest algorithm which find primes in a certain range. This is called The Sieve of Eratosthenes.

Main Idea of Eratosthenes

The main idea behind this algorithm is very simple. Let's try to understand this using an example.

Suppose, you want to find all primes within $20$.

This is basically our algorithm. Below you can find the algorithm for $30$.

Sieve of Eratosthenes
Code to perform this

The code to perform this is quite easy, specially in python, because of the filter function. Let's see the code;

n = 20
all_list = [i for i in range(2,n+1)]
factor_2_remove = filter(lambda m: m %2 !=0, all_list)
factor_2_remove = list(factor_2_remove)
factor_2_remove.append(2)
print(factor_2_remove)
#output:[3, 5, 7, 9, 11, 13, 15, 17, 19, 2]

As you can clearly see, first we have created a list containing a list from $2$ to $n$, then we use filter. This function filter out the numbers which doesn't satisfy the given. Here the condition is $m \not\equiv 0$ mod $2$. This is written as $m%2 !=0$ in python. After using this we again have to add $2$ as it also doesn't satisfy the condition so, it also is removed.

So, to find all primes within any range, we simply do this for all number, not just $2$. You can use a simple for loop for this.

n = 100
all_list = [i for i in range(2,n+1)]
for i in len(all_list):
    first_ele = all_list[0]
    all_list = filter(lambda m: m %first_ele !=0, all_list)
    all_list = list(all_list)
    all_list.append(first_ele)
print(all_list)
#Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

See!, how easy it is.. But we can do even better. Notice, here we have to run the loop $\pi(n)$ times. But we don't have to do that.

Note: $\pi(n)$ is a function, which represent number of primes in between $2$ to $n$.

Remember: If an integer $a>1$ is not divisible by any prime $p\leq \sqrt{a}$, then $a$ is of necessity a prime.

Using this we can increase the efficiency of the program. Let's try to understand this using an example.

Suppose, we want to find primes up to $100$. Then, we create a list up to $100$, i.e., $2,3,4,5,6,7,\cdots ,98,99,100$. Now, we take $2$ and remove all multiples of $2$ from the list, except $2$ itself. We again do the same for $3$, $5$,$\cdots $. But notice $\sqrt{100}=10$, so we just do this up to $10$, i.e., up to $7$. And this will generate all primes within $100$.

If we do this, now the we only have to run the loop for $\pi(n)$ times. Let's see how much the speed has increased. I will now make two functions, one which runs the loop $\pi(n)$ times and one which runs $\pi(\sqrt{n})$ times.

import math as mp
def with_just_sqrtn(n):#uses sqrt n
    all_list = [i for i in range(2,n+1)]
    root_n = mp.ceil(mp.sqrt(n))
    for i in range(n):
        first_ele = all_list[0]
        all_list = filter(lambda m: m %first_ele !=0, all_list)
        all_list = list(all_list)
        all_list.append(first_ele)
        if first_ele == root_n:
            break
    return all_list
print(with_just_sqrtn(100))
#output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]

See, the output is same as before.

The previous one can also be written as a function.

def with_all(n):
    all_list = [i for i in range(2,n+1)]
    for i in range(n):
        first_ele = all_list[0]
        all_list = filter(lambda m: m %first_ele !=0, all_list)
        all_list = list(all_list)
        all_list.append(first_ele)
    return all_list

Now, let's find which one takes much time. We will use $n=1,00,000$

n = 1_00_000
import time
start_t = time.time()
with_all(n)
print("Time = %s seconds"%(time.time()-start_t))
#Output: Time = 131.59189105033875 seconds

Just close to $2$ min $11$ sec. Now, let's run the one with small loop number.

start_t = time.time()
with_just_sqrtn(n)
print("Time = %s seconds"%(time.time()-start_t))
#Output: Time = 0.1107027530670166 seconds

What the !!, just 0.11 sec?

So, i hope now you can see, how much faster it is compared to the previous one.

This is all for today, I hope you have learnt something new.

A simple convergence comparison between Leibniz's and mine pi formula

Author: Kazi Abu Rousan

Here there is $\pi$, there is circle.

Today's blog will be a bit different. This will not discuss any formula or any proof, rather it will just contain a python program to compare a $\pi$ formula given by Leibniz and a one discovered by me (blush).

How does Leibniz formula looks like?

The Leibniz formula for $\pi$ is named after Gottfried Leibniz( published in 1676). Sometimes it is also called Leibniz-Madhava series as this is actually a special case of a more general formula discovered by Madhava of Sangamagrama in 14th century.

The formula is:

$\frac{\pi}{4}$ = $1 - \frac{1}{3}$ + $\frac{1}{5}$ - $\frac{1}{7}$ + $\frac{1}{9}$ -$\cdots$ + $\frac{1}{4n+1}$ - $\frac{1}{4n+3}$ + $\cdots$

If you want a visual proof, read my article : Article- click

or this video: Geometric proof

So, how can you find $\pi$ using this?, Just calculate each fractions and add.

As an example, $4, 4(1-\frac{1}{3}) = 2.6667$, $4(1-\frac{1}{3}$ + $\frac{1}{5}) = 3.4664$, $4(1-\frac{1}{3}$ + $\frac{1}{5}$ - $\frac{1}{7}) =2.895238 $, just like this.

But it is nowhere close to the value of $\pi = 3.141592653\cdots$

The conclusion is that, it converges very slowly. Let's ask a computer to find the value of $\pi$ using the series.

pi_val = 3.1415926535897932#right value upto 17 decimals
calculated_pi_from_series = 0
n = 1000
for i in range(0,n):
    calculated_pi_from_series = calculated_pi_from_series + 1/(4*i+1) - 1/(4*i+3)
calculated_pi_from_series = 4*calculated_pi_from_series
print(calculated_pi_from_series)
print("error = ",pi_val - calculated_pi_from_series)
#output: 3.1410926536210413
#output: error =  0.0004999999687518297

For a output of $3.141592153589724$ and error $= 5.000000689037165e-07$, we need $n$ = $10,00,000$. As you can see slow this series is. But even then it has great mathematical significance. It even has a beautiful geometric relationship with Fermat's two square theorem and prime numbers.

How does my formula looks like?

As it is my own discovery, it doesn't have any name but you may call it Rousan's Formula (🤣🤣). This one is almost identical to Leibniz's formula. It is so as it also uses 2d complex numbers as it's basis just like Leibniz's formula.

The main difference is that it mine uses Eisenstein Integers, i.e., triangular grid while Leibniz's uses Gaussian Integers, i.e., regular square grid.

This formula can be written as :

$\frac{\pi}{3\sqrt{3}}$ = $1 - \frac{1}{2}$ + $\frac{1}{4}$ - $\frac{1}{5}$ + $\frac{1}{7}$ - $\cdots$ + $\frac{1}{3n+1}$ - $\frac{1}{3n+2}$ + $\cdots$

Almost same right?, now let's use python to see how fast it converges.

import math as mp
pi_val = 3.1415926535897932#right value upto 17 decimals
calculated_pi_from_series = 0
n = 1000
for i in range(0,n):
    calculated_pi_from_series = calculated_pi_from_series + 1/(3*i+1) - 1/(3*i+2)
calculated_pi_from_series = 3*calculated_pi_from_series*mp.sqrt(3)
print(calculated_pi_from_series)
print("error = ",pi_val - calculated_pi_from_series)
#output: 3.141015303363362
#output: error =  0.0005773502264312391

For $n = 10,00,000$, we get $3.1415920762392955$ with an error of $5.773504976325228e-07$. So, This shows mine converges a bit more slowly.

A direct comparison and reason

So, why mine converge more slowly?, well it is hidden in it's shape. Mine uses triangular grid and leibniz's uses squares. This is the main reason. But fear not, I have actually found a more generalized version of fermat's two square theorem, by using it i can get another similar series which converges faster than leibniz. Maybe I will discuss that in some later blog.

For now, let's try to plot both series's error. To we will plot the number of terms taken in x axis and error in y axis.

import matplotlib.pyplot as plt
import math as mp
pi_val = 3.1415926535897932
sqrt_3_3 = 3*mp.sqrt(3)

def leib_err(n):
    result = 0
    for i in range(n):
        result = result + 1/(4*i+1) - 1/(4*i+3)
    result = 4*result
    error = pi_val - result
    return result

def rou_err(n):
    result = 0
    for i in range(n):
        result = result + 1/(3*i+1) - 1/(3*i+2)
    result = result*sqrt_3_3
    error = pi_val - result
    return result
n_vals = [i for i in range(10_000+1)]
leibniz = [leib_err(i) for i in n_vals]
# print(leibniz)
rousan  =  [rou_err(i) for i in n_vals]
#
plt.plot(n_vals,leibniz,c='red',label='Leibniz Error')
plt.plot(n_vals,rousan,c='black',label='My formula Error')
plt.legend(loc='best',prop={'size':7})
plt.ylim(3.1375,3.1425)
plt.title("Error vs No. of terms for Leibniz and my $\\pi$ formula.")
plt.show()

The output is:

Error vs no. of terms for Leibniz and my pi formula
Error vs no. of terms for Leibniz and my pi formula - 2

This is all for today, see you guys next time with something new.

AMC 8 2019 Problem 20 | Fundamental Theorem of Algebra

Try out this beautiful algebra problem number 2 from AMC 8 2019 based on the Fundamental Theorem of Algebra.

AMC 8 2019 Problem 20:

How many different real numbers $x$ satisfy the equation\[(x^{2}-5)^{2}=16?\]

$\textbf{(A) }0$
$\textbf{(B) }1$
$\textbf{(C) }2$
$\textbf{(D) }4$
$\textbf{(E) }8$

Key Concepts

Algebra

Value

Telescoping


Check the Answer


Answer: is (D) 4

AMC 8, 2019, Problem 20

Try with Hints


The given equation is

$(x^2-5)^2 = 16$

and that means

$x^2-5 = \pm 4$

Among both cases, if

$x^2-5 = 4$

then,

$x^2 = 9 \implies x = \pm 3$

and that means we have 2 different real numbers that satisfy the equation.

and if we take another case, then

$x^2-5 = -4$

and so,

$x^2 = 1 \implies x = \pm 1$

and that means we have 2 different real numbers in this `case too that satisfy the equation. So total 2+2=4 real numbers that satisfy the equation.

Cheenta Numerates Program for AMC - AIME

Subscribe to Cheenta at Youtube


AMC 8 2019 Problem 16 | Algebra Problem

Try this beautiful Number Theory problem from the AMC 2019 Problem 16. You may use sequential hints to solve the problem.

Algebra Question - AMC 8, 2019 Problem 16

Qiang drives 15 miles at an average speed of 30 miles per hour. How many additional miles will he have to drive at 55 miles per hour to average 50 miles per hour for the entire trip?
(A) 45
(B) 62
(C) 90
(D) 110
(E) 135

Key Concepts

Algebra

Value

Average Speed


Check the Answer


Answer: is (D) 110

AMC 8, 2019, Problem 16

Try with Hints


Among the options, there is only one option which is divisible by 55 and that is 110.

That option tells the travel hour is 2.

Qiang drives 15 miles at an average speed of 30 miles per hour.

And we know, Average speed = Total Distance/Total Time

So, by the formula,

$\frac{15}{30} + \frac{110}{55} = \frac{5}{2}$

In this case, If we consider the whole journey, Total Distance is (110+15)=125

And as Qiang has to drive at 50 miles per hour for the entire trip, and as Average speed = Total Distance/Total Time ,

$\frac{125}{50} = \frac{5}{2}$

As both are same , our answer 110 is established.

Cheenta Numerates Program for AMC - AIME

Subscribe to Cheenta at Youtube


AMC 8 2019 Problem 17 | Value of Product

Try out this beautiful algebra problem from AMC 8, 2019 based on finding the value of the product. You may use sequential hints to solve the problem.

AMC 8 2019: Problem 17


What is the value of the product

$\left(\frac{1 \cdot 3}{2 \cdot 2}\right)\left(\frac{2 \cdot 4}{3 \cdot 3}\right)\left(\frac{3 \cdot 5}{4 \cdot 4}\right) \cdots\left(\frac{97 \cdot 99}{98 \cdot 98}\right)\left(\frac{98 \cdot 100}{99 \cdot 99}\right) ?$

(A) $\frac{1}{2}$


(B) $\frac{50}{99}$


(C) $\frac{9800}{9801}$


(D) $\frac{100}{99}$


(E) $50$


Key Concepts

Algebra

Value

Telescoping


Check the Answer


Answer: is $\frac{50}{99}$

AMC 8, 2019, Problem 17

Try with Hints


We write

$\left(\frac{1.3}{2.2}\right)\left(\frac{2.4}{3.3}\right)\left(\frac{3.5}{4.4}\right) \ldots\left(\frac{97.99}{98.98}\right)\left(\frac{98.100}{99.99}\right)$

in a different form like


$\frac{1}{2} \cdot\left(\frac{3.2}{2.3}\right) \cdot\left(\frac{4.3}{3.4}\right) \cdots \cdots \left(\frac{99.98}{98.99}\right) \cdot \frac{100}{99}$

All of the middle terms eliminate each other, and only the first and last term remains i.e.

$\frac{1}{2} \cdot \frac{100}{99}$

$\frac{1}{2} \cdot \frac{100}{99}=\frac{50}{99}$

and that is the final answer.

Cheenta Numerates Program for AMC - AIME

Subscribe to Cheenta at Youtube


National Mathematics Talent Contest (NMTC) 2022

What is National Mathematics Talent Contest ?

The National Mathematics Talent Contest or NMTC is a national-level mathematics contest conducted by the Association of Mathematics Teachers of India (AMTI).

Aim of the contest:

To find and encourage students who have the ability for original and creative thinking, preparedness to tackle unknown and non-routine problems having a general mathematical ability suitable to their level.

Who can appear for NMTC 2022?

The contest is for students of different levels. Here is the breakdown for the same:

The contest is available in English only.

Exam fee (2022):

Syllabus

The syllabus of the National Mathematics Talent Contest (NMTC) is similar to the syllabus of the Mathematics Olympiad (Regional, National and International level). It includes:

For Primary:

For Sub-Junior:

For Junior:

For Inter:

For Senior:

It is a three hours long examination containing subjective questions and it is based on the syllabus of B.Sc. mathematics course.

Important Dates, NMTC 2022:

Last Date for entries: 1st October 2022

Stage-1 Preliminary Test

Stage-2 Final Test

What does the winner of NMTC get?

There will be cash awards for the top three winners in each level at the final followed by merit certificates for them and others selected at the final level.

Books required to prepare for NMTC:

Since the exam require preparation for Math Olympiad level, you can click on this link and get all the books necessary for NMTC.

For more information about the exam, you may visit the official website: https://zurl.co/AsSO

How to Prepare for NMTC 2022?

The students are encouraged to practice non-routine problems, asked in exams like PRMO, RMO, INMO and IMO.

Cheenta is teaching outstanding kids for Math Olympiads from 4 continents since 10 years now. So, we got the expertise and we want you to utilize it for your benefit.

You can contact us and know more about our course work by filling up a form here: https://cheenta.com/contact-us/.

See you!

Nearest value | PRMO 2018 | Question 14

Try this beautiful problem from the PRMO, 2018 based on Nearest value.

Nearest Value - PRMO 2018


If x=cos1cos2cos3.....cos89 and y=cos2cos6cos10....cos86, then what is the integer nearest to \(\frac{2}{7}log_2{\frac{y}{x}}\)?

  • is 107
  • is 19
  • is 840
  • cannot be determined from the given information

Key Concepts


Algebra

Numbers

Multiples

Check the Answer


Answer: is 19.

PRMO, 2018, Question 14

Higher Algebra by Hall and Knight

Try with Hints


\(\frac{y}{x}\)=\(\frac{cos2cos6cos10.....cos86}{cos1cos2cos3....cos89}\)

=\(2^{44}\times\sqrt{2}\frac{cos2cos6cos10...cos86}{sin2sin4...sin88}\)

[ since cos\(\theta\)=sin(90-\(\theta\)) from cos 46 upto cos 89 and 2sin\(\theta\)cos\(\theta\)=sin2\(\theta\)]

=\(\frac{2^{\frac{89}{2}}sin4sin8sin12...sin88}{sin2sin4sin6...sin88}\)

[ since sin\(\theta\)=cos(90-\(\theta\))]

=\(\frac{2^{\frac{89}{2}}}{cos4cos8cos12..cos88}\)

[ since cos\(\theta\)=sin(90-\(\theta\))]

=\(\frac{2^\frac{89}{2}}{\frac{1}{2}^{22}}\)

[since \(cos4cos8cos12...cos88\)

\(=(cos4cos56cos64)(cos8cos52cos68)(cos12cos48cos72)(cos16cos44cos76)(cos20cos40cos80)(cos24cos36cos84)(cos28cos32cos88)cos60\)

\(=(1/2)^{15}(cos12cos24cos36cos48cos60cos72cos84)\)

\(=(1/2)^{16}(cos12cos48cos72)(cos24cos36cos84)\)

\(=(1/2)^{20}(cos36cos72)\)

\(=(1/2)^{20}(cos36sin18)\)

\(=(1/2)^{22}(4sin18cos18cos36/cos18)\)

\(=(1/2)^{22}(sin72/cos18)\)

\(=(1/2)^{22}\)]

=\(2^\frac{133}{2}\)

\(\frac{2}{7}log_2{\frac{y}{x}}\)=\(\frac{2}{7} \times \frac{133}{2}\)=19.

Subscribe to Cheenta at Youtube


Sequence and permutations | AIME II, 2015 | Question 10

Try this beautiful problem from the American Invitational Mathematics Examination I, AIME II, 2015 based on Sequence and permutations.

Sequence and permutations - AIME II, 2015


Call a permutation \(a_1,a_2,....,a_n\) of the integers 1,2,...,n quasi increasing if \(a_k \leq a_{k+1} +2\) for each \(1 \leq k \leq n-1\), find the number of quasi increasing permutations of the integers 1,2,....,7.

  • is 107
  • is 486
  • is 840
  • cannot be determined from the given information

Key Concepts


Sequence

Permutations

Integers

Check the Answer


Answer: is 486.

AIME II, 2015, Question 10

Elementary Number Theory by David Burton

Try with Hints


While inserting n into a string with n-1 integers, integer n has 3 spots where it can be placed before n-1, before n-2, and at the end

Number of permutations with n elements is three times the number of permutations with n-1 elements

or, number of permutations for n elements=3 \(\times\) number of permutations of (n-1) elements

or, number of permutations for n elements=\(3^{2}\) number of permutations of (n-2) elements

......

or, number of permutations for n elements=\(3^{n-2}\) number of permutations of {n-(n-2)} elements

or, number of permutations for n elements=2 \(\times\) \(3^{n-2}\)

forming recurrence relation as the number of permutations =2 \(\times\) \(3^{n-2}\)

for n=3 all six permutations taken and go up 18, 54, 162, 486

for n=7, here \(2 \times 3^{5} =486.\)

Header text

as

Header text

sds

Subscribe to Cheenta at Youtube


Numbers of positive integers | AIME I, 2012 | Question 1

Try this beautiful problem from the American Invitational Mathematics Examination, AIME 2012 based on Numbers of positive integers.

Numbers of positive integers - AIME 2012


Find the number of positive integers with three not necessarily distinct digits, \(abc\), with \(a \neq 0\) and \(c \neq 0\) such that both \(abc\) and \(cba\) are multiples of \(4\).

  • is 107
  • is 40
  • is 840
  • cannot be determined from the given information

Key Concepts


Integers

Number Theory

Algebra

Check the Answer


Answer: is 40.

AIME, 2012, Question 1.

Elementary Number Theory by David Burton .

Try with Hints


Here a number divisible by 4 if a units with tens place digit is divisible by 4

Then case 1 for 10b+a and for 10b+c gives 0(mod4) with a pair of a and c for every b

[ since abc and cba divisible by 4 only when the last two digits is divisible by 4 that is 10b+c and 10b+a is divisible by 4]

and case II 2(mod4) with a pair of a and c for every b

Then combining both cases we get for every b gives a pair of a s and a pair of c s

So for 10 b's with 2 a's and 2 c's for every b gives \(10 \times 2 \times 2\)

Then number of ways \(10 \times 2 \times 2\) = 40 ways.

Subscribe to Cheenta at Youtube


Number of points and planes | AIME I, 1999 | Question 10

Try this beautiful problem from the American Invitational Mathematics Examination I, AIME I, 1999 based on Number of points and planes.

Number of points and planes - AIME I, 1999


Ten points in the plane are given with no three collinear. Four distinct segments joining pairs of three points are chosen at random, all such segments being equally likely.The probability that some three of the segments form a triangle whose vertices are among the ten given points is \(\frac{m}{n}\) where m and n are relatively prime positive integers, find m+n.

  • is 107
  • is 489
  • is 840
  • cannot be determined from the given information

Key Concepts


Number of points

Plane

Probability

Check the Answer


Answer: is 489.

AIME I, 1999, Question 10

Geometry Vol I to IV by Hall and Stevens

Try with Hints


\(10 \choose 3\) sets of 3 points which form triangles,

fourth distinct segment excluding 3 segments of triangles=45-3=42

Required probability=\(\frac{{10 \choose 3} \times 42}{45 \choose 4}\)

where \({45 \choose 4}\) is choosing 4 segments from 45 segments

=\(\frac{16}{473}\) then m+n=16+473=489.

Subscribe to Cheenta at Youtube