All about Fibonacci: A python approach

Size: px
Start display at page:

Download "All about Fibonacci: A python approach"

Transcription

1 World Applied Programming, Vol (1), No (1), April ISSN: WAP journal. All about Fibonacci: A python approach C. Canaan * M. S. Garai M. Daya Information institute Information institute Information institute Chiredzi, Zimbabwe Chiredzi, Zimbabwe Chiredzi, Zimbabwe canaancan@gmail.com mat.s.g@mail.com d2020m@yahoo.com Abstract: Here we want to represent a brief introduction to Fibonacci sequence and different techniques for generating and calculating the value of this sequence. So, first we will make you familiar with Fibonacci numbers and then proposed algorithms in python language will be represented. Mathematical definitions are also placed for clarifying the matter. Key word: Fibonacci Fibonacci numbers Fibonacci algorithms Fibonacci generation I. INTRODUCTION Leonardo Pisano Bigollo (c c. 1250) [1] also known as Leonardo of Pisa, Leonardo Pisano, Leonardo Bonacci, Leonardo Fibonacci, or, most commonly, simply Fibonacci, was an Italian mathematician, considered by some "the most talented western mathematician of the Middle Ages" [2]. Fibonacci is best known to the modern world for [3] the spreading of the Hindu-Arabic numeral system in Europe, primarily through the publication in the early 13th century of his Book of Calculation, the Liber Abaci; and for a number sequence named after him known as the Fibonacci numbers, which he did not discover but used as an example in the Liber Abaci [4]. In the Liber Abaci (1202), Fibonacci introduces the so-called modus Indorum (method of the Indians), today known as Arabic numerals (Sigler 2003; Grimm 1973). The book advocated numeration with the digits 0 9 and place value. The book showed the practical importance of the new numeral system, using lattice multiplication and Egyptian fractions, by applying it to commercial bookkeeping, conversion of weights and measures, the calculation of interest, money-changing, and other applications. The book was well received throughout educated Europe and had a profound impact on European thought. Liber Abaci also posed, and solved, a problem involving the growth of a population of rabbits based on idealized assumptions. The solution, generation by generation, was a sequence of numbers later known as Fibonacci numbers. The number sequence was known to Indian mathematicians as early as the 6th century [5] [6] [7], but it was Fibonacci's Liber Abaci that introduced it to the West. In the Fibonacci sequence of numbers, each number is the sum of the previous two numbers, starting with 0 and 1. This sequence begins 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, [8] The higher up in the sequence, the closer two consecutive "Fibonacci numbers" of the sequence divided by each other will approach the golden ratio (approximately 1 : or : 1). After this short introduction, we are going to introduce Fibonacci sequence algorithms in the following sections. II. FIBONACCI NUMBERS AND RELATED ALGORITHMS The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21,..., in which each item is formed by adding the previous two. The sequence can be defined recursively by Fibonacci number programs that implement this definition directly are often used as introductory examples of recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also exist. The recursive definition can be translated directly into Python as follows: 72

2 <<fibonacci_recursive.py>>= if n == 0: return 0 elif n == 1: return 1 return fib(n-1) + fib(n-2) Although the recursive implementation given above is elegant and close to the mathematical definition, it is not very practical. Calculating fib(n) requires calculating two smaller Fibonacci numbers, which in turn require two additional recursive calls each, and so on until all branches reach 1. As a consequence, the time required to calculate fib(n) is exponential in n (it is about Φn, where Φ is the golden ratio). Interestingly, when computing fib(n), the for all 1<k<n fib(k) is called fib(n-k) times, but fib(0) is called fib(n-2) times. To remedy this, we can employ memoization to cache previous computations. The memoization cache is a dictionary consisting of entries composed of a key n and a corresponding value fib(n). We initialize the dictionary with the first two Fibonacci numbers: <<fibonacci_memo.py>>= memo = {0:0, 1:1} The memoized fib function recursively computes and stores the value of fib(n) if it hasn't been previously stored in the memo dictionary. Otherwise it simply returns the memoized value of fib(n). <<fibonacci_memo.py>>= if not n in memo: memo[n] = fib(n-1) + fib(n-2) return memo[n] To calculate the nth Fibonacci number in only n steps, we can also start with 0 and 1 and iteratively add up items n times: <<fibonacci_iteration.py>>= a, b = 0, 1 for i in range(n): a, b = b, a + b return a We can also construct a generator that calculates and yields the Fibonacci numbers one at a time: <<fibonacci_generator.py>>= def fib(): a, b = 0, 1 while 1: yield a a, b = b, a + b All sequences defined by linear recurrence have an associated closed-form expression for the nth number. The Fibonacci numbers in particular are given by Binet's formula (for Jacques Philippe Marie Binet) 73

3 where is the golden ratio, This can be implemented straightforwardly: <<fibonacci_binet.py>>= phi = (1 + 5**0.5) / 2 return int(round((phi**n - (1-phi)**n) / 5**0.5)) Because of floating-point rounding errors, this will however only give the right result for n < 70. Binet's formula can be inverted by ignoring the term, which disappears for large n. We can therefore define the inverse Fibonacci function that, when given F(n), returns n (ignoring that F(1) = F(2)): <<fibonacci_binet.py>>= from math import log def fibinv(f): if f < 2: return f return int(round(log(f * 5**0.5) / log(phi))) Here rounding is used to our advantage: it removes the error introduced by our modification to Binet's formula. The function will in fact return the right answer when given any Fibonacci number that can be stored as an exact integer in the computer's memory. On the other hand, it does not verify that the given number actually is a Fibonacci number; inputting a large Fibonacci number or any number close to it will give the same result. This may be useful, for example to find the Fibonacci number closest to a given number. There are efficient ways to calculate the nth Fibonacci number exactly without first calculating all its predecessors. One way to do so is to utilize the matrix identity and employing exponentiation by squaring to find the nth power of the left-hand matrix. We here represent a 2-by-2 matrix A as the 3-tuple (a, b, c) where <<fibonacci_matrix.py>>= def mul(a, B): a, b, c = A d, e, f = B return a*d + b*e, a*e + b*f, b*e + c*f def pow(a, n): if n == 1: return A if n & 1 == 0: return pow(mul(a, A), n//2) return mul(a, pow(mul(a, A), (n-1)//2)) if n < 2: return n return pow((1,1,0), n-1)[0] Our next approach to quick computation of large Fibonacci number is based on representation of as, where L n is n-th Lucas number and Fn is n-th Fibonacci number. It is easy to obtain 74

4 formulas necessary for exponentiation by squaring. For example:. Therefore, F 2n = L n F n. Similar, and. <<fibonacci_lf.py>>= def powlf(n): if n == 1: return (1, 1) L, F = powlf(n//2) L, F = (L**2 + 5*F**2) >> 1, L*F if n & 1: return ((L + 5*F)>>1, (L + F) >>1) return (L, F) return powlf(n)[1] Notes: (1) The code can be imporved: it is not necessary to calculate L n on the last step. if n & 1: return powlf(n)[1] L, F = powlf(n // 2) return L * F (2) The choice of power (**2) over multiplication is based on experiments (this way program is 10% faster). (3) It is obvious how to rework this algorithm to the iterative one at the expense of its clarity. Using a method developed by [9] we can iterate, for large numbers, very few times (for F1000 we only need 22 iterations) <<fibonacci_ewd.py>>= fibs = {0: 0, 1: 1} if n in fibs: return fibs[n] if n % 2 == 0: fibs[n] = ((2 * fib((n / 2) - 1)) + fib(n / 2)) * fib(n / 2) return fibs[n] fibs[n] = (fib((n - 1) / 2) ** 2) + (fib((n+1) / 2) ** 2) return fibs[n] At the expense of immediate legibility, we can compute Fibonacci numbers way faster than naive methods. Uses caching of results both for speed and to define starting values. REFERENCES [1] The Fibonacci Series - Biographies - Leonardo Fibonacci (ca ca.1240)". Library.thinkquest.org. Retrieved [2] Howard Eves. An Introduction to the History of Mathematics. Brooks Cole, 1990: ISBN (6th ed.), p 261. [3] Leonardo Pisano - page 3: "Contributions to number theory". Encyclopædia Britannica Online, Retrieved 18 September [4] Parmanand Singh. "Acharya Hemachandra and the (so called) Fibonacci Numbers". Math. Ed. Siwan, 20(1):28-30, ISSN

5 [5] Susantha Goonatilake (1998). Toward a Global Science. Indiana University Press. p ISBN [6] Donald Knuth (2006). The Art of Computer Programming: Generating All Trees History of Combinatorial Generation; Volume 4. Addison-Wesley. p. 50. ISBN [7] Rachel W. Hall. Math for poets and drummers. Math Horizons 15 (2008) [8] Fibonacci Numbers from The On-Line Encyclopedia of Integer Sequences. [9] E. W. Dijkstra (found at 76

CSC 8301 Design and Analysis of Algorithms: Recursive Analysis

CSC 8301 Design and Analysis of Algorithms: Recursive Analysis CSC 8301 Design and Analysis of Algorithms: Recursive Analysis Professor Henry Carter Fall 2016 Housekeeping Quiz #1 New TA office hours: Tuesday 1-3 2 General Analysis Procedure Select a parameter for

More information

Fibonacci numbers introduce vectors, functions and recursion. An exercise introduces graphics user interfaces.

Fibonacci numbers introduce vectors, functions and recursion. An exercise introduces graphics user interfaces. Chapter 2 Fibonacci Numbers Fibonacci numbers introduce vectors, functions and recursion. An exercise introduces graphics user interfaces. Leonardo Pisano Fibonacci was born around 1170 and died around

More information

Divide and Conquer Strategy. (Page#27)

Divide and Conquer Strategy. (Page#27) MUHAMMAD FAISAL MIT 4 th Semester Al-Barq Campus (VGJW01) Gujranwala faisalgrw123@gmail.com Reference Short Questions for MID TERM EXAMS CS502 Design and Analysis of Algorithms Divide and Conquer Strategy

More information

Algorithms in Systems Engineering ISE 172. Lecture 1. Dr. Ted Ralphs

Algorithms in Systems Engineering ISE 172. Lecture 1. Dr. Ted Ralphs Algorithms in Systems Engineering ISE 172 Lecture 1 Dr. Ted Ralphs ISE 172 Lecture 1 1 References for Today s Lecture Required reading Chapter 1 References D.E. Knuth, The Art of Computer Programming,

More information

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1

# track total function calls using a global variable global fibcallcounter fibcallcounter +=1 Math 4242 Fibonacci, Memoization lecture 13 Today we talk about a problem that sometimes occurs when using recursion, and a common way to fix it. Recall the Fibonacci sequence (F 0, F 1, F 2,...) that

More information

The power of logarithmic computations. Recursive x y. Calculate x y. Can we reduce the number of multiplications?

The power of logarithmic computations. Recursive x y. Calculate x y. Can we reduce the number of multiplications? Calculate x y The power of logarithmic computations // Pre: x 0, y 0 // Returns x y int power(int x, int y) { int p = 1; for (int i = 0; i < y; ++i) p = p x; return p; Jordi Cortadella Department of Computer

More information

Twelve Simple Algorithms to Compute Fibonacci Numbers

Twelve Simple Algorithms to Compute Fibonacci Numbers arxiv:1803.07199v2 [cs.ds] 13 Apr 2018 Twelve Simple Algorithms to Compute Fibonacci Numbers Ali Dasdan KD Consulting Saratoga, CA, USA alidasdan@gmail.com April 16, 2018 Abstract The Fibonacci numbers

More information

Measuring Efficiency

Measuring Efficiency Growth Announcements Measuring Efficiency Recursive Computation of the Fibonacci Sequence Our first example of tree recursion: fib(3) fib(5) fib(4) def fib(n): if n == 0: return 0 elif n == 1: return 1

More information

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming

Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming Emil Sekerinski, McMaster University, Winter Term 16/17 COMP SCI 1MD3 Introduction to Programming In Python, variables are names of objects base 5 >>> base = 5 >>> height = 4 >>> area = base*height/2 >>>

More information

Math 4242 Fibonacci, Memoization lecture 13

Math 4242 Fibonacci, Memoization lecture 13 Math 4242 Fibonacci, Memoization lecture 13 Today we talk about a problem that sometimes occurs when using recursion, and a common way to fix it. Recall the Fibonacci sequence (F 1, F 2,...) that occurs

More information

Fibonacci Numbers. An Exercise in Assembly Language Programming. Andreas Klappenecker. September 7, 2004

Fibonacci Numbers. An Exercise in Assembly Language Programming. Andreas Klappenecker. September 7, 2004 Fibonacci Numbers An Exercise in Assembly Language Programming Andreas Klappenecker September 7, 2004 1 Introduction Leonardo Pisano (1170 1250) was a scholar born in Pisa in Italy, who is probably better

More information

Dr. Chuck Cartledge. 15 July 2015

Dr. Chuck Cartledge. 15 July 2015 Miscellanea 6.5 Fun with Fibonacci Break 1.5 Exam Conclusion References CSC-205 Computer Organization Lecture #008 Chapter 6, section 5, Chapter 1, section 5 Dr. Chuck Cartledge 15 July 2015 1/30 Table

More information

Finding matchings in sequences. Sarah Holliday Southern Polytechnic State University

Finding matchings in sequences. Sarah Holliday Southern Polytechnic State University Finding matchings in sequences Sarah Holliday Southern Polytechnic State University Finding matchings that occur in sequences Sarah Holliday Southern Polytechnic State University Sequences in matchings

More information

Dr. Chuck Cartledge. 24 Oct. 2017

Dr. Chuck Cartledge. 24 Oct. 2017 4.4 Fun with Fibonacci Chap. 4 review Conclusion References Files CSC-205 Computer Organization Lecture #010 Section 4.4, Gates and machine instructions Dr. Chuck Cartledge 24 Oct. 2017 1/19 Table of contents

More information

Introduction to Python Programming

Introduction to Python Programming advances IN SYSTEMS AND SYNTHETIC BIOLOGY 2018 Anna Matuszyńska Oliver Ebenhöh oliver.ebenhoeh@hhu.de Ovidiu Popa ovidiu.popa@hhu.de Our goal Learning outcomes You are familiar with simple mathematical

More information

The Citizen s Guide to Dynamic Programming

The Citizen s Guide to Dynamic Programming The Citizen s Guide to Dynamic Programming Jeff Chen Stolen extensively from past lectures October 6, 2007 Unfortunately, programmer, no one can be told what DP is. You have to try it for yourself. Adapted

More information

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling

Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling Recursion Identify recursive algorithms Write simple recursive algorithms Understand recursive function calling With reference to the call stack Compute the result of simple recursive algorithms Understand

More information

Algorithms in Systems Engineering IE170. Lecture 2. Dr. Ted Ralphs

Algorithms in Systems Engineering IE170. Lecture 2. Dr. Ted Ralphs Algorithms in Systems Engineering IE170 Lecture 2 Dr. Ted Ralphs IE170 Lecture 2 1 References for Today s Lecture Required reading CLRS Chapter 1 References D.E. Knuth, The Art of Computer Programming,

More information

UC Berkeley CS 170: Efficient Algorithms and Intractable Problems Handout 1 Lecturer: Michael Jordan August 28, Notes 1 for CS 170

UC Berkeley CS 170: Efficient Algorithms and Intractable Problems Handout 1 Lecturer: Michael Jordan August 28, Notes 1 for CS 170 UC Berkeley CS 170: Efficient Algorithms and Intractable Problems Handout 1 Lecturer: Michael Jordan August 28, 2005 Notes 1 for CS 170 1 Topics to be covered 1. Data Structures and big-o Notation: a quick

More information

Chapter 5: Recursion

Chapter 5: Recursion Chapter 5: Recursion Objectives Looking ahead in this chapter, we ll consider Recursive Definitions Function Calls and Recursive Implementation Anatomy of a Recursive Call Tail Recursion Nontail Recursion

More information

Recurrences and Memoization: The Fibonacci Sequence

Recurrences and Memoization: The Fibonacci Sequence Chapter 7 Recurrences and Memoization: The Fibonacci Sequence Copyright Oliver Serang, 208 University of Montana Department of Computer Science The Fibonacci sequence occurs frequently in nature and has

More information

TILING PROBLEMS: FROM DOMINOES, CHECKERBOARDS, AND MAZES TO DISCRETE GEOMETRY

TILING PROBLEMS: FROM DOMINOES, CHECKERBOARDS, AND MAZES TO DISCRETE GEOMETRY TILING PROBLEMS: FROM DOMINOES, CHECKERBOARDS, AND MAZES TO DISCRETE GEOMETRY BERKELEY MATH CIRCLE 1. Looking for a number Consider an 8 8 checkerboard (like the one used to play chess) and consider 32

More information

MEMOIZATION, RECURSIVE DATA, AND SETS

MEMOIZATION, RECURSIVE DATA, AND SETS MEMOIZATION, RECURSIVE DATA, AND SETS 4b COMPUTER SCIENCE 61A July 18, 2013 1 Memoization Later in this class, you ll learn about orders of growth and how to analyze exactly how efficient (or inefficient)

More information

Version: = =

Version: = = Chapter 4 Dynamic programming By Sariel Har-Peled, November 8, 018 1 The events of 8 September prompted Foch to draft the later legendary signal: My centre is giving way, my right is in retreat, situation

More information

A LISP programmer knows the value of everything, but the cost of nothing.

A LISP programmer knows the value of everything, but the cost of nothing. Chapter 6 Cost A LISP programmer knows the value of everything, but the cost of nothing. Alan Perlis The evaluation rules in Chapter 3 explain how to determine the value of every expression that can be

More information

Data Structures and Algorithms

Data Structures and Algorithms Data Structures and Algorithms Luciano Bononi Computer Science Engineering University of Bologna bononi@cs.unibo.it http://www.cs.unibo.it/~bononi/ Slide credits: these slides have been translated from

More information

The Knapsack Problem an Introduction to Dynamic Programming. Slides based on Kevin Wayne / Pearson-Addison Wesley

The Knapsack Problem an Introduction to Dynamic Programming. Slides based on Kevin Wayne / Pearson-Addison Wesley The Knapsack Problem an Introduction to Dynamic Programming Slides based on Kevin Wayne / Pearson-Addison Wesley Different Problem Solving Approaches Greedy Algorithms Build up solutions in small steps

More information

Midterm solutions. n f 3 (n) = 3

Midterm solutions. n f 3 (n) = 3 Introduction to Computer Science 1, SE361 DGIST April 20, 2016 Professors Min-Soo Kim and Taesup Moon Midterm solutions Midterm solutions The midterm is a 1.5 hour exam (4:30pm 6:00pm). This is a closed

More information

Algorithms: Why and How. Dr. Ted Ralphs

Algorithms: Why and How. Dr. Ted Ralphs Algorithms: Why and How Dr. Ted Ralphs Algorithms: Why and How 1 What is an Algorithm? Algorithms: Why and How 1 What is an Algorithm? According to Webster s Collegiate Dictionary: A procedure for solving

More information

UNIT B3 Number Sequences: Activities

UNIT B3 Number Sequences: Activities B Number Sequences Activities Activities B. Lines B. Regular Polygons B. Towers B.4 Fibonacci Sequence Notes and Solutions ( page) ACTIVITY B. Lines If three lines are arranged as in the diagram, there

More information

BBM 101. Introduction to Programming I. Lecture #06 Recursion

BBM 101. Introduction to Programming I. Lecture #06 Recursion BBM 101 Introduction to Programming I Lecture #06 Recursion Aykut Erdem, Fuat Akal & Aydın Kaya // Fall 2018 Last time Collections, File I/O Lists a = [ 3, 2*2, 10-1 ] b = [ 5, 3, 'hi' ] c = [ 4, 'a',

More information

Agenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution

Agenda. The worst algorithm in the history of humanity. Asymptotic notations: Big-O, Big-Omega, Theta. An iterative solution Agenda The worst algorithm in the history of humanity 1 Asymptotic notations: Big-O, Big-Omega, Theta An iterative solution A better iterative solution The repeated squaring trick Fibonacci sequence 2

More information

The Running Time of Programs

The Running Time of Programs The Running Time of Programs The 90 10 Rule Many programs exhibit the property that most of their running time is spent in a small fraction of the source code. There is an informal rule that states 90%

More information

Fruitful Recursion (recursion that returns a value)

Fruitful Recursion (recursion that returns a value) Recall: fruitful functions and side effects Fruitful Recursion (recursion that returns a value) max, min len, int Recursive func,ons today: sumup factorial countdownlist fibrec countuplist upperrightrepeat

More information

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization

Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute. Module 02 Lecture - 45 Memoization Design and Analysis of Algorithms Prof. Madhavan Mukund Chennai Mathematical Institute Module 02 Lecture - 45 Memoization Let us continue our discussion of inductive definitions. (Refer Slide Time: 00:05)

More information

Analysis of Algorithms. CSE Data Structures April 10, 2002

Analysis of Algorithms. CSE Data Structures April 10, 2002 Analysis of Algorithms CSE 373 - Data Structures April 10, 2002 Readings and References Reading Chapter 2, Data Structures and Algorithm Analysis in C, Weiss Other References 10-Apr-02 CSE 373 - Data Structures

More information

i.e.: n! = n (n 1)

i.e.: n! = n (n 1) Recursion and Java Recursion is an extremely powerful problemsolving technique. Problems that at first appear difficult often have simple recursive solutions. Recursion breaks a problems into several smaller

More information

Decorators in Python

Decorators in Python Decorators in Python Need to measure timing of algorithms Measure execution time Wall-clock timing: Import a clock or time module Save current time Execute function Save current time Difference between

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College October 11, 2017 Outline Outline 1 Chapter 6: Recursion Outline Chapter 6: Recursion 1 Chapter 6: Recursion Measuring Complexity

More information

Recursive Definitions

Recursive Definitions Recursion Objectives Explain the underlying concepts of recursion Examine recursive methods and unravel their processing steps Explain when recursion should and should not be used Demonstrate the use of

More information

major differences are that the graph of a sequence is discrete and you can obtain some values of sequences using a recursive defi nition.

major differences are that the graph of a sequence is discrete and you can obtain some values of sequences using a recursive defi nition. Lesson 3-7 Graphs of Sequences Vocabulary Fibonacci sequence BIG IDEA Sequences are graphed like other functions The major differences are that the graph of a sequence is discrete and you can obtain some

More information

Chapter 5: Recursion. Objectives

Chapter 5: Recursion. Objectives Chapter 5: Recursion Objectives Looking ahead in this chapter, we ll consider Recursive Definitions Function Calls and Recursive Implementation Anatomy of a Recursive Call Tail Recursion Nontail Recursion

More information

Chapter 5: Recursion

Chapter 5: Recursion Chapter 5: Recursion Objectives Looking ahead in this chapter, we ll consider Recursive Definitions Function Calls and Recursive Implementation Anatomy of a Recursive Call Tail Recursion Nontail Recursion

More information

Recall from Last Time: Big-Oh Notation

Recall from Last Time: Big-Oh Notation CSE 326 Lecture 3: Analysis of Algorithms Today, we will review: Big-Oh, Little-Oh, Omega (Ω), and Theta (Θ): (Fraternities of functions ) Examples of time and space efficiency analysis Covered in Chapter

More information

A NEW SEQUENCE DERIVED FROM A COMBINATION OF CUBES WITH VOLUME F 3 n

A NEW SEQUENCE DERIVED FROM A COMBINATION OF CUBES WITH VOLUME F 3 n A NEW SEQUENCE DERIVED FROM A COMBINATION OF CUBES WITH VOLUME F n JOSEPH S. OZBOLT Abstract. An arrangement of cubes with volume F n, similar to the arrangement made with squares developing the Fibonacci

More information

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016

RECURSION 3. 1 Recursion COMPUTER SCIENCE 61A. June 30, 2016 RECURSION 3 COMPUTER SCIENCE 61A June 30, 2016 A recursive function is a function that calls itself. Here s a recursive function: def factorial(n): if n == 0 or n == 1: return 1 else: return n * factorial(n-1)

More information

General Purpose Methods for Combinatorial Optimization

General Purpose Methods for Combinatorial Optimization General Purpose Methods for Combinatorial Optimization 0/7/00 Maximum Contiguous Sum 3-4 9 6-3 8 97-93 -3 84 Σ = 87 Given:... N Z, at least one i > 0 ind i, j such that j k k = i is maximal 0/7/00 0/7/00

More information

Python review. 1 Python basics. References. CS 234 Naomi Nishimura

Python review. 1 Python basics. References. CS 234 Naomi Nishimura Python review CS 234 Naomi Nishimura The sections below indicate Python material, the degree to which it will be used in the course, and various resources you can use to review the material. You are not

More information

Analysis of Algorithms & Big-O. CS16: Introduction to Algorithms & Data Structures Spring 2018

Analysis of Algorithms & Big-O. CS16: Introduction to Algorithms & Data Structures Spring 2018 Analysis of Algorithms & Big-O CS16: Introduction to Algorithms & Data Structures Spring 2018 Outline Running time Big-O Big-Ω and Big-Θ Analyzing Seamcarve Dynamic programming Fibonacci sequence 2 Algorithms

More information

CSC-140 Assignment 4

CSC-140 Assignment 4 CSC-140 Assignment 4 Please do not Google a solution to these problem, cause that won t teach you anything about programming - the only way to get good at it, and understand it, is to do it! 1 Introduction

More information

Mathematics. Jaehyun Park. CS 97SI Stanford University. June 29, 2015

Mathematics. Jaehyun Park. CS 97SI Stanford University. June 29, 2015 Mathematics Jaehyun Park CS 97SI Stanford University June 29, 2015 Outline Algebra Number Theory Combinatorics Geometry Algebra 2 Sum of Powers n k=1 k 3 k 2 = 1 n(n + 1)(2n + 1) 6 = ( k ) 2 = ( 1 2 n(n

More information

Student Outcomes. Lesson Notes. Classwork. Discussion (4 minutes)

Student Outcomes. Lesson Notes. Classwork. Discussion (4 minutes) Student Outcomes Students write mathematical statements using symbols to represent numbers. Students know that written statements can be written as more than one correct mathematical sentence. Lesson Notes

More information

CS 97SI: INTRODUCTION TO PROGRAMMING CONTESTS. Jaehyun Park

CS 97SI: INTRODUCTION TO PROGRAMMING CONTESTS. Jaehyun Park CS 97SI: INTRODUCTION TO PROGRAMMING CONTESTS Jaehyun Park Today s Lecture Algebra Number Theory Combinatorics (non-computational) Geometry Emphasis on how to compute Sum of Powers n k=1 k 2 = 1 6 n(n

More information

ENVIRONMENT DIAGRAMS AND RECURSION 2

ENVIRONMENT DIAGRAMS AND RECURSION 2 ENVIRONMENT DIAGRAMS AND RECURSION 2 COMPUTER SCIENCE 61A February 4, 2016 1 Environment Diagrams An environment diagram keeps track of all the variables that have been defined and the values they are

More information

Behind the Scenes Programming for Engineers Winter 2015

Behind the Scenes Programming for Engineers Winter 2015 Behind the Scenes ing for Engineers Winter 205 Andreas Zeller, Saarland University Today s Topics Variables Assignments Computing models Storing Values We want to store values during computations We want

More information

Introduction to Computer Science

Introduction to Computer Science Introduction to Computer Science Algorithms and data structures Piotr Fulmański Faculty of Mathematics and Computer Science, University of Łódź, Poland November 19, 2008 Table of Contents 1 Algorithm 2

More information

61A Lecture 4. Monday, September 9

61A Lecture 4. Monday, September 9 61A Lecture 4 Monday, September 9 Announcements Homework 1 due Tuesday 9/10 at 5pm; Late homework is not accepted! Quiz on Wednesday 9/11 released at 1pm, due Thursday 9/12 at 11:59pm Open-computer: You

More information

Combinatorial Interpretations of Spanning Tree Identities

Combinatorial Interpretations of Spanning Tree Identities Combinatorial Interpretations of Spanning Tree Identities Arthur T. Benjamin and Carl R. Yerger November 14, 2004 Abstract We present a combinatorial proof that the wheel graph W n has L 2n 2 spanning

More information

Choice of C++ as Language

Choice of C++ as Language EECS 281: Data Structures and Algorithms Principles of Algorithm Analysis Choice of C++ as Language All algorithms implemented in this book are in C++, but principles are language independent That is,

More information

Discussion on Writing of Recursive Algorithm

Discussion on Writing of Recursive Algorithm , pp.127-134 http://dx.doi.org/10.14257/ijhit.2013.6.6.11 Discussion on Writing of Recursive Algorithm Song Jinping Computer Department, Jining Teachers College, Wulanchabu, China jnsongjinping@126.com

More information

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion

Outline. Simple Recursive Examples Analyzing Recursion Sorting The Tower of Hanoi Divide-and-conquer Approach In-Class Work. 1 Chapter 6: Recursion Outline 1 A Function Can Call Itself A recursive definition of a function is one which makes a function call to the function being defined. The function call is then a recursive function call. A definition

More information

CMSC 451: Lecture 10 Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct 3, 2017

CMSC 451: Lecture 10 Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct 3, 2017 CMSC 45 CMSC 45: Lecture Dynamic Programming: Weighted Interval Scheduling Tuesday, Oct, Reading: Section. in KT. Dynamic Programming: In this lecture we begin our coverage of an important algorithm design

More information

A Survey of Mathematics with Applications 8 th Edition, 2009

A Survey of Mathematics with Applications 8 th Edition, 2009 A Correlation of A Survey of Mathematics with Applications 8 th Edition, 2009 South Carolina Discrete Mathematics Sample Course Outline including Alternate Topics and Related Objectives INTRODUCTION This

More information

Bioinformatics. Gabriella Trucco.

Bioinformatics. Gabriella Trucco. Bioinformatics Gabriella Trucco Email: gabriella.trucco@unimi.it Organization Course times: Tuesday 9:30-13:00 Language: English Webpage: http://homes.di.unimi.it/trucco/bioinformatics will include: current

More information

Turbo Charge CPU Utilization in Fork/Join Using the ManagedBlocker

Turbo Charge CPU Utilization in Fork/Join Using the ManagedBlocker 1 Turbo Charge CPU Utilization in Fork/Join Using the ManagedBlocker 2017 Heinz Kabutz, All Rights Reserved Dr Heinz M. Kabutz Last Updated 2017-01-24 2 Regular 3 ManagedBlocker 4 Speeding Up Fibonacci

More information

Recursion. Dr. Jürgen Eckerle FS Recursive Functions

Recursion. Dr. Jürgen Eckerle FS Recursive Functions Recursion Dr. Jürgen Eckerle FS 2008 Recursive Functions Recursion, in mathematics and computer science, is a method of defining functions in which the function being defined is applied within its own

More information

CGF Lecture 2 Numbers

CGF Lecture 2 Numbers CGF Lecture 2 Numbers Numbers A number is an abstract entity used originally to describe quantity. i.e. 80 Students etc The most familiar numbers are the natural numbers {0, 1, 2,...} or {1, 2, 3,...},

More information

Overview. CSE 101: Design and Analysis of Algorithms Lecture 1

Overview. CSE 101: Design and Analysis of Algorithms Lecture 1 Overview CSE 101: Design and Analysis of Algorithms Lecture 1 CSE 101: Design and analysis of algorithms Course overview Logistics CSE 101, Fall 2018 2 First, relevant prerequisites Advanced Data Structures

More information

HOMEWORK FILE SOLUTIONS

HOMEWORK FILE SOLUTIONS Data Structures Course (CSCI-UA 102) Professor Yap Spring 2012 HOMEWORK FILE February 13, 2012 SOLUTIONS 1 Homework 2: Due on Thu Feb 16 Q1. Consider the following function called crossproduct: int crossproduct(int[]

More information

CSCI 121: Recursive Functions & Procedures

CSCI 121: Recursive Functions & Procedures CSCI 121: Recursive Functions & Procedures Sorting quizzes Every time I give a quiz, I need to enter grades into my gradebook. My grading sheet is organized alphabetically. So I sort the papers alphabetically,

More information

DM502 Programming A. Peter Schneider-Kamp.

DM502 Programming A. Peter Schneider-Kamp. DM502 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm502/! Python & Linux Install Party Tomorrow (Tuesday, September 12) from 10 14 Fredagsbar (area south of Kantine

More information

UNIT 1 PLACE VALUE AND WHOLE NUMBERS

UNIT 1 PLACE VALUE AND WHOLE NUMBERS UNIT 1 PLACE VALUE AND WHOLE NUMBERS INTRODUCTION We will begin our study of Arithmetic by learning about the number system we use today. The Base-10 Number System or Hindu-Arabic Numeral System began

More information

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) )

def F a c t o r i a l ( n ) : i f n == 1 : return 1 else : return n F a c t o r i a l ( n 1) def main ( ) : print ( F a c t o r i a l ( 4 ) ) 116 4.5 Recursion One of the most powerful programming techniques involves a function calling itself; this is called recursion. It is not immediately obvious that this is useful; take that on faith for

More information

A New Line Drawing Algorithm Based on Sample Rate Conversion

A New Line Drawing Algorithm Based on Sample Rate Conversion A New Line Drawing Algorithm Based on Sample Rate Conversion c 2002, C. Bond. All rights reserved. February 5, 2002 1 Overview In this paper, a new method for drawing straight lines suitable for use on

More information

i W E I R D U T O P I A i

i W E I R D U T O P I A i i W E I R D U T O P I A i CHAPTER 9 1 EXPLODING DOTS CHAPTER 9 WEIRD AND WILD MACHINES All right. It is time to go wild and crazy. Here is a whole host of quirky and strange machines to ponder on, some

More information

(Refer Slide Time: 02:59)

(Refer Slide Time: 02:59) Numerical Methods and Programming P. B. Sunil Kumar Department of Physics Indian Institute of Technology, Madras Lecture - 7 Error propagation and stability Last class we discussed about the representation

More information

International Journal of Advance Research in Computer Science and Management Studies

International Journal of Advance Research in Computer Science and Management Studies Volume 2, Issue 8, August 2014 ISSN: 2321 7782 (Online) International Journal of Advance Research in Computer Science and Management Studies Research Article / Survey Paper / Case Study Available online

More information

Beyond the Euler Trail. Mathematics is often thought of as formulas, ratios, and the number Pi. The history of

Beyond the Euler Trail. Mathematics is often thought of as formulas, ratios, and the number Pi. The history of Patino 1 Prof. Petersen Sierra Patino Math 101 Section 4939 6 April 2016 Beyond the Euler Trail Mathematics is often thought of as formulas, ratios, and the number Pi. The history of math and its roots

More information

Lecture 12: Dynamic Programming Part 1 10:00 AM, Feb 21, 2018

Lecture 12: Dynamic Programming Part 1 10:00 AM, Feb 21, 2018 CS18 Integrated Introduction to Computer Science Fisler, Nelson Lecture 12: Dynamic Programming Part 1 10:00 AM, Feb 21, 2018 Contents 1 Introduction 1 2 Fibonacci 2 Objectives By the end of these notes,

More information

Programming & Data Structure

Programming & Data Structure Functions Programming & Data Structure CS 11002 Partha Bhowmick http://cse.iitkgp.ac.in/ pb CSE Department IIT Kharagpur Spring 2012-2013 Functions Callee : Caller = Bowler : Captain Functions int f(){...

More information

UNIT 5B Binary Search

UNIT 5B Binary Search 205/09/30 UNIT 5B Binary Search Course Announcements Written exam next week (Wed. Oct 7 ) Practice exam available on the Resources page Exam reviews: Sunday afternoon; watch Piazza for times and places

More information

UNIT 5A Recursion: Basics. Recursion

UNIT 5A Recursion: Basics. Recursion UNIT 5A Recursion: Basics 1 Recursion A recursive function is one that calls itself. Infinite loop? Not necessarily. 2 1 Recursive Definitions Every recursive definition includes two parts: Base case (non

More information

RECURSION, RECURSION, (TREE) RECURSION! 3

RECURSION, RECURSION, (TREE) RECURSION! 3 RECURSION, RECURSION, (TREE) RECURSION! 3 COMPUTER SCIENCE 61A September 18, 2013 A function is recursive if it calls itself. Below is recursive factorial function. def factorial(n): if n == 0 or n ==

More information

Dynamic Programming. Introduction, Weighted Interval Scheduling, Knapsack. Tyler Moore. Lecture 15/16

Dynamic Programming. Introduction, Weighted Interval Scheduling, Knapsack. Tyler Moore. Lecture 15/16 Dynamic Programming Introduction, Weighted Interval Scheduling, Knapsack Tyler Moore CSE, SMU, Dallas, TX Lecture /6 Greedy. Build up a solution incrementally, myopically optimizing some local criterion.

More information

1.3. Conditional expressions To express case distinctions like

1.3. Conditional expressions To express case distinctions like Introduction Much of the theory developed in the underlying course Logic II can be implemented in a proof assistant. In the present setting this is interesting, since we can then machine extract from a

More information

Multithreaded Algorithms Part 1. Dept. of Computer Science & Eng University of Moratuwa

Multithreaded Algorithms Part 1. Dept. of Computer Science & Eng University of Moratuwa CS4460 Advanced d Algorithms Batch 08, L4S2 Lecture 11 Multithreaded Algorithms Part 1 N. H. N. D. de Silva Dept. of Computer Science & Eng University of Moratuwa Announcements Last topic discussed is

More information

Arithmetic Algorithms Taught in Schools

Arithmetic Algorithms Taught in Schools Arithmetic Algorithms Taught in Schools Joint Mathematics Meetings Baltimore January 15-18, 2014 Patricia Baggett Andrzej Ehrenfeucht Dept. of Math Sci. Computer Science Dept. New Mexico State Univ. University

More information

PROGRAMMING RECURRENCE RELATIONS

PROGRAMMING RECURRENCE RELATIONS PAWEL SOBOCINSKI, UNIVERSITY OF SOUTHAMPTON U HAWAII @ MANOA, SEPTEMBER, 6 4:PM-:PM, POST 6 PROGRAMMING RECURRENCE RELATIONS BASED ON JOINT WORK WITH FILIPPO BONCHI AND FABIO ZANASI . LEONARDO OF PISA

More information

Today: Amortized Analysis (examples) Multithreaded Algs.

Today: Amortized Analysis (examples) Multithreaded Algs. Today: Amortized Analysis (examples) Multithreaded Algs. COSC 581, Algorithms March 11, 2014 Many of these slides are adapted from several online sources Reading Assignments Today s class: Chapter 17 (Amortized

More information

Artificial Intelligence Lecture 1

Artificial Intelligence Lecture 1 Artificial Intelligence Lecture 1 istrative Matters Webpage: www.aass.oru.se/~mbl/ai Examiner: Mathias Broxvall Assistant: Lia Susana d.c. Silva Lopez Schedule 20 hours/week on this course. 4 hours lectures,

More information

Extended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation

Extended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation Extended Introduction to Computer Science CS1001.py Lecture 7: Basic Algorithms: Sorting, Merge; Time Complexity and the O( ) notation Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal

More information

Outline. Computer Science 331. Desirable Properties of Hash Functions. What is a Hash Function? Hash Functions. Mike Jacobson.

Outline. Computer Science 331. Desirable Properties of Hash Functions. What is a Hash Function? Hash Functions. Mike Jacobson. Outline Computer Science 331 Mike Jacobson Department of Computer Science University of Calgary Lecture #20 1 Definition Desirable Property: Easily Computed 2 3 Universal Hashing 4 References Mike Jacobson

More information

CS1 Lecture 15 Feb. 18, 2019

CS1 Lecture 15 Feb. 18, 2019 CS1 Lecture 15 Feb. 18, 2019 HW4 due Wed. 2/20, 5pm Q2 and Q3: it is fine to use a loop as long as the function is also recursive. Exam 1, Thursday evening, 2/21, 6:30-8:00pm, W290 CB You must bring ID

More information

CSC-140 Assignment 5

CSC-140 Assignment 5 CSC-140 Assignment 5 Please do not Google a solution to these problems, cause that won t teach you anything about programming - the only way to get good at it, and understand it, is to do it! 1 Introduction

More information

Language of the Machine Recursive functions

Language of the Machine Recursive functions EECS 322 Computer Architecture Language of the Machine Recursive functions Instructor: Francis G. Wolff wolff@eecs.cwru.edu Case Western Reserve University This presentation uses powerpoint animation:

More information

APCS-AB: Java. Recursion in Java December 12, week14 1

APCS-AB: Java. Recursion in Java December 12, week14 1 APCS-AB: Java Recursion in Java December 12, 2005 week14 1 Check point Double Linked List - extra project grade Must turn in today MBCS - Chapter 1 Installation Exercises Analysis Questions week14 2 Scheme

More information

PHY224 Practical Physics I. Lecture 2

PHY224 Practical Physics I. Lecture 2 PHY224 Practical Physics I Python Review Lecture 2 Sept. 19 20 20, 2013 Summary Functions and Modules Graphs (plotting with Pylab) Scipy packages References M H. Goldwasser, D. Letscher: Object oriented

More information

DAVID CALLAN. Department of Statistics. Medical Science Center University Ave. September 21, Abstract

DAVID CALLAN. Department of Statistics. Medical Science Center University Ave. September 21, Abstract On Conjugates for Set Partitions and Integer Compositions DAVID CALLAN Department of Statistics University of Wisconsin-Madison Medical Science Center 1300 University Ave Madison, WI 53706-1532 callan@stat.wisc.edu

More information

COMP 161 Lecture Notes 16 Analyzing Search and Sort

COMP 161 Lecture Notes 16 Analyzing Search and Sort COMP 161 Lecture Notes 16 Analyzing Search and Sort In these notes we analyze search and sort. Counting Operations When we analyze the complexity of procedures we re determine the order of the number of

More information

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp

DM550/DM857 Introduction to Programming. Peter Schneider-Kamp DM550/DM857 Introduction to Programming Peter Schneider-Kamp petersk@imada.sdu.dk http://imada.sdu.dk/~petersk/dm550/ http://imada.sdu.dk/~petersk/dm857/ Project Qualification Assessment first assessment

More information