Python Lecture 2-Fundamental-Algorithms
Python Lecture 2-Fundamental-Algorithms
(contd)
Sine function as series
• Problem
Evaluate sin(x) as a series expansion i.e, upto n
terms
term = x
sum = x
i=1
y = x*x
error = 0.00001
while (abs(term) > error) do
i=i+2
term = -term*y/(i*(i-1)
sum = sum + term
end-while
output sum
Square Root (x)
• Problem
Find square root of x.
Source:https://ocw.mit.edu/courses/electrical-engineering-and-computer-science/6-0001-introduction-to-computer-science-and-
programming-in-python-fall-2016/lecture-slides-code/
Fibonacci series
• Problem
Generate and print first n terms of Fibonacci
sequence, which looks like
0, 1, 1, 2, 3, 5, 8, 13 ….
An improved version:
0, 1, 1, 2, 3, 5, 8, 13 ….
a=0 a=a+b
b=1 b=a+b
Fibonacci series
input n
a=0
An improved version!
b=1
i=2 # keeps track of number of terms decided
while i<n do
output(a,b)
a=a+b
b=a+b
i=i+2
end-while
if i==n then output (a,b) else output a
Reverse Digits of (x)
• Problem
Given a positive integer, reverse the order of its digit.
Input 17653
Outpur 35671
• Problem
Given a positive integer, reverse the order of its digit.
• Problem
Given two positive non-zero integers n and m find
their greatest common divisor
m = 18, n = 30
gcd = 6
Greatest Common Divisor (gcd)
• Problem
Given two positive non-zero integers n and m find
their greatest common divisor
input n , m
variable r
while r > 0
r = n mod m
n=m
m=r
end while
output n
Smallest Exact Divisor
• Problem
Given an integer n find its smallest exact divisor
other than 1
Option 1
start from 2, 3, 4, 5, … till n
check if n is exactly divided
input n
for i = 2 to n
if n mod i == 0
break
end for
output i
Smallest Exact Divisor
• Problem
Given an integer n find its smallest exact divisor
other than 1
Option 2
When a number s exactly divides n, there exists another
number b that also exactly divides n
36
s b sxb=n
2 18
3 12
4 9
6 6 b=s so here sxs=n
Smallest Exact Divisor
Option 2
If n is even the smallest divisor is 2!
Input n
if n mod 2 == 0
s=2
else
d=3
r = sqrt(n)
while ((n mod d != 0) and (d<r))
d = d+2
end while
if n mod d == 0
s=d
else
s=1