Recall: d is a divisor of n n % d == 0 last digit of n last = n % 10 removing last digit n = n // 10 adding digit to n n = n * 10 + digit How to solve a problem? identify inputs and outputs find the calculations, selection and repetitions to solve it
A function is a piece of code introduced by def that: Python functions Python programs are made of a sequence of functions. These function can be called within the program or outside in the shell. A function is a piece of code introduced by def that: Has a name Has some arguments which are the inputs Returns some values which are the outputs Has some code to calculate the outputs from the inputs
The function head starts with def and finished with : def functionName(arg1, arg2, …): statem1 statem2 … return output # end functionName The function head starts with def and finished with : The function body calculates the output from the input args The output is returned. The function is called by its name output = functionName(a1,a2,..)
Function to calculate the min, max values of a and b. - inputs: a, b are arguments - output: min, max must returned - how to calculate? Use an if selection
def minMax(a, b) : ‘’’ function to calculate the max and min values of a and b. ‘’’ if a>b : max, min = a, b else: max, min = b, a # endif return min, max # end minMax
‘’’ find the max value for a,b,c,d.’’’ min1, max1 = minMax(a,b) Function to calculate the maximum value of 4 numbers a, b, c, d. def maximum4(a,b,c,d) : ‘’’ find the max value for a,b,c,d.’’’ min1, max1 = minMax(a,b) min2, max2 = minMax(c,d) min, max = minMax(max1, max2) return max # end maximum4
Functions are written once and used multiple times.
Prime numbers n is prime when: 1) it has only 2 divisors 1 and n 2) it has not any proper divisor in range of 2, 3, 4,…, sqrt(n)
Write a function to test if a number n is prime. - input: n - output: ans - how to do it? 1) test 2 ans = True 3) test even number ans = False 4) repeat for a potential odd divisor 3,5,.., ? if d is a divisor then ans = False ans = true
def isPrime(n): ‘’’ function to test primality.’’’ if n == 1 : return False # endif if n == 2 : return True #endif for d in range(3, math.sqrt(n)+1;2) : if n % d == 0 : return False # endif #endfor return True
The Euclidian Algorithm Find the gcd of 2 numbers a, b. Solutions: Find prime decomposition and choose the common primes with the smallest exponents a = 2**4 * 3**2 * 5 and b = 2 * 5 **2 gcd = 2 ** 1 * 5 **1 Euclidian algorithm does consecutive divisions Divide a to b to find res and rem Change a = b and b = rem
Example a = 56 and b = 40 1) a = 56, b= 40 res = a // b = 1 rem = a % b = 16 2) a = 40, b = 16 res = a // b = 2 rem = a%b =8 3) a = 16, b = 8 res = a//b = 2 rem = a%b =0 4) a = 8, b = 0 repetition stops gcd = 8 the last remainder different than 0
The number of division in the algorithm is log (max(a,b)) hence just few divisions.