# Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Save this PDF as:

Size: px
Start display at page:

Download "Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC"

## Transcription

1 Introduction to Programming (in C++) Loops Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

2 Example Assume the following specification: Input: read a number N > 0 Output: write the sequence N (one number per line) This specification suggests some algorithm with a repetitive procedure. Introduction to Programming Dept. CS, UPC 2

3 The while statement Syntax: while ( condition ) statement; (the condition must return a Boolean value) Semantics: Similar to the repetition of an if statement The condition is evaluated: If true, the statement is executed and the control returns to the while statement again. If false, the while statement terminates. Introduction to Programming Dept. CS, UPC 3

4 Write the numbers 1 N // Input: read a number N > 0 // Output: write the numbers 1...N (one per line) int main() { int N; cin >> N; int i = 1; while (i <= N) { // The numbers 1..i-1 have been written cout << i << endl; i = i + 1; Introduction to Programming Dept. CS, UPC 4

5 Product of two numbers //Input: read two non-negative numbers x and y //Output: write the product x y // Constraint: do not use the operator // The algorithm calculates the sum x+x+x+ +x (y times) int main() { int x, y; cin >> x >> y; // Let x=a, y=b int p = 0; // Invariant: A B = p + x y while (y > 0) { p = p + x; y = y 1; cout << p << endl; Introduction to Programming Dept. CS, UPC 5

6 A quick algorithm for the product Let p be the product x y Observation If y is even, p = (x 2) (y/2) If y is odd, p = x (y-1) + x and (y-1) becomes even Example: = 646 x y p Introduction to Programming Dept. CS, UPC 6

7 A quick algorithm for the product int main() { int x, y; cin >> x >> y; // Let x=a, y=b int p = 0; // Invariant: A B = p + x y while (y > 0) { if (y%2 == 0) { x = x 2; y = y/2; else { p = p + x; y = y 1; cout << p << endl; x y p Introduction to Programming Dept. CS, UPC 7

8 Why is the quick product interesting? Most computers have a multiply instruction in their machine language. The operations x 2 and y/2 can be implemented as 1-bit left and right shifts, respectively. So, the multiplication can be implemented with shift and add operations. The quick product algorithm is the basis for hardware implementations of multipliers and mimics the paper-and-pencil method learned at school (but using base 2). Introduction to Programming Dept. CS, UPC 8

9 Quick product in binary: example 77 x 41 = x Introduction to Programming Dept. CS, UPC 9

10 Counting a s We want to read a text represented as a sequence of characters that ends with. We want to calculate the number of occurrences of the letter a We can assume that the text always has at least one character (the last. ) Example: the text Programming in C++ is amazingly easy!. has 4 a s Introduction to Programming Dept. CS, UPC 10

11 Counting a s // Input: sequence of characters that ends with. // Output: number of times a appears in the // sequence int main() { char c; cin >> c; int count = 0; // Inv: count is the number of a s in the visited // prefix of the sequence. c contains the next // non-visited character while (c!=. ) { if (c == a ) count = count + 1; cin >> c; cout << count << endl; Introduction to Programming Dept. CS, UPC 11

12 Counting digits We want to read a non-negative integer and count the number of digits (in radix 10) in its textual representation. Examples digits digits 8 1 digit 0 1 digit (note this special case) Introduction to Programming Dept. CS, UPC 12

13 Counting digits // Input: a non-negative number N // Output: number of digits in N (0 has 1 digit) int main() { int N; cin >> N; int ndigits = 0; // Inv: ndigits contains the number of digits in the // tail of the number, N contains the remaining // part (head) of the number while (N > 9) { ndigits = ndigits + 1; N = N/10; // extracts one digit cout << ndigits + 1 << endl; Introduction to Programming Dept. CS, UPC 13

14 Properties Euclid s algorithm for gcd gcd(a,a)=a If a > b, then gcd(a,b) = gcd(a-b,b) Example a b gcd (114, 42) Introduction to Programming Dept. CS, UPC 14

15 Euclid s algorithm for gcd // Input: read two positive numbers (a and b) // Output: write gcd(a,b) int main() { int a, b; cin >> a >> b; // Let a=a, b=b // gcd(a,b) = gcd(a,b) while (a!= b) { if (a > b) a = a b; else b = b a; cout << a << endl; Introduction to Programming Dept. CS, UPC 15

16 Faster Euclid s algorithm for gcd Properties gcd(a, 0)=a If b > 0 then gcd(a, b) = gcd(b, a mod b) Example a b Introduction to Programming Dept. CS, UPC 16

17 Faster Euclid s algorithm for gcd // Input: read two positive numbers (a and b) // Output: write gcd(a,b) int main() { int a, b; cin >> a >> b; // Let a=a, b=b // gcd(a,b) = gcd(a,b) while (b!= 0) { int r = a%b; a = b; b = r; // Guarantees b < a (loop termination) cout << a << endl; Introduction to Programming Dept. CS, UPC 17

18 Efficiency of Euclid s algorithm How many iterations will Euclid s algorithm need to calculate gcd(a,b) in the worst case (assume a > b)? Subtraction version: a iterations (consider gcd(1000,1)) Modulo version: 5 d(b) iterations, where d(b) is the number of digits of b represented in base 10 (proof by Gabriel Lamé, 1844) Introduction to Programming Dept. CS, UPC 18

19 Solving a problem several times In many cases, we might be interested in solving the same problem for several input data. Example: calculate the gcd of several pairs of natural numbers. Input Output Introduction to Programming Dept. CS, UPC 19

20 Solving a problem several times // Input: several pairs of natural numbers at the input // Output: the gcd of each pair of numbers written at the output int main() { int a, b; // Inv: the gcd of all previous pairs have been // calculated and written at the output while (cin >> a >> b) { // A new pair of numbers from the input while (b!= 0) { int r = a%b; a = Calculate b; gcd(a,b) and b = r; write the result into cout cout << a << endl; Introduction to Programming Dept. CS, UPC 20

21 Solving a problem several times // Input: several pairs of natural numbers at the input // Output: the gcd of each pair of numbers written at the output int main() { int a, b; // Inv: the gcd of all previous pairs have been // calculated and written at the output while (cin >> a >> b) { // A new pair of numbers from the input while (b!= 0) { int r = a%b; a = b; b = r; cout << a << endl; Introduction to Programming Dept. CS, UPC 21

22 Prime number A prime number is a natural number that has exactly two distinct divisors: 1 and itself. (Comment: 1 is not prime) Write a program that reads a natural number (N) and tells whether it is prime or not. Algorithm: try all potential divisors from 2 to N-1 and check whether the remainder is zero. Introduction to Programming Dept. CS, UPC 22

23 Prime number // Input: read a natural number N>0 // Output: write is prime or is not prime depending on // the primality of the number int main() { int N; cin >> N; int divisor = 2; bool is_prime = (N!= 1); // 1 is not prime, 2 is prime, the rest enter the loop (assume prime) // is_prime is true while a divisor is not found // and becomes false as soon as the first divisor is found while (divisor < N) { if (N%divisor == 0) is_prime = false; divisor = divisor + 1; if (is_prime) cout << is prime << endl; else cout << is not prime << endl; Introduction to Programming Dept. CS, UPC 23

24 Prime number Observation: as soon as a divisor is found, there is no need to check divisibility with the rest of the divisors. However, the algorithm tries all potential divisors from 2 to N-1. Improvement: stop the iteration when a divisor is found. Introduction to Programming Dept. CS, UPC 24

25 Prime number // Input: read a natural number N>0 // Output: write is prime or is not prime depending on // the primality of the number int main() { int N; cin >> N; int divisor = 2; bool is_prime = (N!= 1); while (is_prime and divisor < N) { is_prime = N%divisor!= 0; divisor = divisor + 1; if (is_prime) cout << is prime << endl; else cout << is not prime << endl; Introduction to Programming Dept. CS, UPC 25

26 Prime number: doing it faster If N is not prime, we can find two numbers, a and b, such that: N = a b, with 1 < a b <N and with the following property: a N There is no need to find divisors up to N-1. We can stop much earlier. Note: a N is equivalent to a 2 N Introduction to Programming Dept. CS, UPC 26

27 Prime number: doing it faster // Input: read a natural number N>0 // Output: write is prime or is not prime depending on // the primality of the number int main() { int N; cin >> N; int divisor = 2; bool is_prime = (N!= 1); while (is_prime and divisor divisor <= N) { is_prime = N%divisor!= 0; divisor = divisor + 1; if (is_prime) cout << is prime << endl; else cout << is not prime << endl; Introduction to Programming Dept. CS, UPC 27

28 Is there any real difference? Iterations Number of bits Introduction to Programming Dept. CS, UPC 28

29 In real time (N= ) > time prime_slow < number is prime u 0.004s 0: % > time prime_fast < number is prime 0.004u 0.000s 0: % Introduction to Programming Dept. CS, UPC 29

30 The for statement Very often we encounter loops of the form: i = N; while (i <= M) { do_something; i = i + 1; This can be rewritten as: for (i = N; i <= M; i = i + 1) { do_something; Introduction to Programming Dept. CS, UPC 30

31 The for statement In general for ( S_init ; condition ; S_iter ) S_body ; is equivalent to: S_init; while ( condition ) { S_body ; S_iter ; Introduction to Programming Dept. CS, UPC 31

32 Writing the numbers in an interval // Input: read two integer numbers, N and M, // such that N <= M. // Output: write all the integer numbers in the // interval [N,M] int main() { int N, M; cin >> N >> M; for (int i = N; i <= M; ++i) cout << i << endl; Variable declared within the scope of the loop Autoincrement operator Introduction to Programming Dept. CS, UPC 32

33 Calculate x y // Input: read two integer numbers, x and y, such that y >= 0 // Output: write x y int main() { int x, y; cin >> x >> y; int p = 1; for (int i = 0; i < y; ++i) p = p x; cout << p << endl; Introduction to Programming Dept. CS, UPC 33

34 Drawing a triangle Given a number n (e.g. n = 6), we want to draw this triangle: * ** *** **** ***** ****** Introduction to Programming Dept. CS, UPC 34

35 Drawing a triangle // Input: read a number n > 0 // Output: write a triangle of size n int main() { int n; cin >> n; // Inv: the rows 1..i-1 have been written for (int i = 1; i <= n; ++i) { // Inv: written j-1 times in row i for (int j = 1; j <= i; ++j) cout << ; cout << endl; Introduction to Programming Dept. CS, UPC 35

36 Perfect numbers A number n > 0 is perfect if it is equal to the sum of all its divisors except itself. Examples 6 is a perfect number (1+2+3 = 6) 12 is not a perfect number ( ) Strategy Keep adding divisors until the sum exceeds the number or there are no more divisors. Introduction to Programming Dept. CS, UPC 36

37 Perfect numbers // Input: read a number n > 0 // Output: write a message indicating // whether it is perfect or not int main() { int n; cin >> n; int sum = 0, d = 1; // Inv: sum is the sum of all divisors until d-1 while (d <= n/2 and sum <= n) { if (n%d == 0) sum += d; d = d + 1; if (sum == n) cout << is perfect << endl; else cout << is not perfect << endl; Introduction to Programming Dept. CS, UPC 37

38 Perfect numbers Would the program work using the following loop condition? while (d <= n/2 and sum < n) Can we design a more efficient version without checking all the divisors until n/2? Clue: consider the most efficient version of the program to check whether a number is prime. Introduction to Programming Dept. CS, UPC 38

### Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Example Introduction to Programming (in C++) Loops Assume the following specification: Input: read a number N > 0 Output: write the sequence 1 2 3 N (one number per line) Jordi Cortadella, Ricard Gavaldà,

### Introduction to Programming (in C++) Subprograms: procedures and functions

Introduction to Programming (in C++) Subprograms: procedures and functions Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Subprograms Programming languages, in particular

### 8 Primes and Modular Arithmetic

8 Primes and Modular Arithmetic 8.1 Primes and Factors Over two millennia ago already, people all over the world were considering the properties of numbers. One of the simplest concepts is prime numbers.

### Introduction to Programming (in C++) Conclusions. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Conclusions Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Why is programming hard? Part of the difficulty is that we have many requirements.

### Introduction to Programming (in C++) Data types and visibility. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. Computer Science, UPC

Introduction to Programming (in C++) Data types and visibility Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. Computer Science, UPC Outline Data types Type conversion Visibility Introduction to

### Repetition and Loops. Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed.

New Topic Repetition and Loops Additional Python constructs that allow us to effect the (1) order and (2) number of times that program statements are executed. These constructs are the 1. while loop and

### Elementary Number Theory and Methods of Proof. CSE 215, Foundations of Computer Science Stony Brook University http://www.cs.stonybrook.

Elementary Number Theory and Methods of Proof CSE 215, Foundations of Computer Science Stony Brook University http://www.cs.stonybrook.edu/~cse215 1 Number theory Properties: 2 Properties of integers (whole

### Integers and division

CS 441 Discrete Mathematics for CS Lecture 12 Integers and division Milos Hauskrecht milos@cs.pitt.edu 5329 Sennott Square Symmetric matrix Definition: A square matrix A is called symmetric if A = A T.

### The Euclidean Algorithm

The Euclidean Algorithm A METHOD FOR FINDING THE GREATEST COMMON DIVISOR FOR TWO LARGE NUMBERS To be successful using this method you have got to know how to divide. If this is something that you have

### Homework 5 Solutions

Homework 5 Solutions 4.2: 2: a. 321 = 256 + 64 + 1 = (01000001) 2 b. 1023 = 512 + 256 + 128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = (1111111111) 2. Note that this is 1 less than the next power of 2, 1024, which

### Today s Topics. Primes & Greatest Common Divisors

Today s Topics Primes & Greatest Common Divisors Prime representations Important theorems about primality Greatest Common Divisors Least Common Multiples Euclid s algorithm Once and for all, what are prime

### 3 Structure of Modular Multiplication

3 Structure of Modular Multiplication Unlike addition, multiplication in Z M is fairly strange. There may not always be an inverse, you can multiply two non-zero numbers together and get zero, and in general

### CS 103X: Discrete Structures Homework Assignment 3 Solutions

CS 103X: Discrete Structures Homework Assignment 3 s Exercise 1 (20 points). On well-ordering and induction: (a) Prove the induction principle from the well-ordering principle. (b) Prove the well-ordering

### Introduction to Programming

Introduction to Programming SS 2012 Adrian Kacso, Univ. Siegen adriana.dkacsoa@duni-siegena.de Tel.: 0271/740-3966, Office: H-B 8406 Stand: April 25, 2012 Betriebssysteme / verteilte Systeme Introduction

### The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

The C++ Language Loops Loops! Recall that a loop is another of the four basic programming language structures Repeat statements until some condition is false. Condition False True Statement1 2 1 Loops

### What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

What is a Loop? CSC Intermediate Programming Looping A loop is a repetition control structure It causes a single statement or a group of statements to be executed repeatedly It uses a condition to control

### 6.096 Lab 1. Due: 7 January 12:30:00. September 20, 2011

6.096 Lab 1 Due: 7 January 1:30:00 September 0, 011 1 Additional Material 1.1 Constants A constant is an expressions with a fixed value. Kinds of constants: Literals: used to express particular values

### 8 Divisibility and prime numbers

8 Divisibility and prime numbers 8.1 Divisibility In this short section we extend the concept of a multiple from the natural numbers to the integers. We also summarize several other terms that express

### CSI 333 Lecture 1 Number Systems

CSI 333 Lecture 1 Number Systems 1 1 / 23 Basics of Number Systems Ref: Appendix C of Deitel & Deitel. Weighted Positional Notation: 192 = 2 10 0 + 9 10 1 + 1 10 2 General: Digit sequence : d n 1 d n 2...

### Sports tournament. Introduction to Programming (in C++) Advanced examples. Sports tournament. Sports tournament

Introduction to Programming (in C++) Advanced examples Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Design a program that reads the participants in a knockout tournament

### Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

Name: Class: Date: Exam #1 - Prep True/False Indicate whether the statement is true or false. 1. Programming is the process of writing a computer program in a language that the computer can respond to

### Factoring Algorithms

Factoring Algorithms The p 1 Method and Quadratic Sieve November 17, 2008 () Factoring Algorithms November 17, 2008 1 / 12 Fermat s factoring method Fermat made the observation that if n has two factors

### Homework until Test #2

MATH31: Number Theory Homework until Test # Philipp BRAUN Section 3.1 page 43, 1. It has been conjectured that there are infinitely many primes of the form n. Exhibit five such primes. Solution. Five such

### QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall-2015 1

QUIZ-II Write a program that mimics a calculator. The program should take as input two integers and the operation to be performed. It should then output the numbers, the operator, and the result. (For

### Practice Problems for First Test

Mathematicians have tried in vain to this day to discover some order in the sequence of prime numbers, and we have reason to believe that it is a mystery into which the human mind will never penetrate.-

### Mathematical Methods and Numerical Techniques I Homework Problems

Physics Department Spring 2006 Bryn Mawr College Assignment #4 Physics 206 February 9, 2006 Mathematical Methods and Numerical Techniques I Homework Problems 1. Reading Assignment Read Boas, remaining

### Discrete Mathematics and Probability Theory Fall 2009 Satish Rao, David Tse Note 5

CS 70 Discrete Mathematics and Probability Theory Fall 2009 Satish Rao, David Tse Note 5 Modular Arithmetic One way to think of modular arithmetic is that it limits numbers to a predefined range {0,1,...,N

### Introduction to Programming (in C++) Multi-dimensional vectors. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Multi-dimensional vectors Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Matrices A matrix can be considered a two-dimensional vector,

### Mathematical induction & Recursion

CS 441 Discrete Mathematics for CS Lecture 15 Mathematical induction & Recursion Milos Hauskrecht milos@cs.pitt.edu 5329 Sennott Square Proofs Basic proof methods: Direct, Indirect, Contradiction, By Cases,

### Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Boolean Expressions, Conditions, Loops, and Enumerations Relational Operators == // true if two values are equivalent!= // true if two values are not equivalent < // true if left value is less than the

### Course notes on Number Theory

Course notes on Number Theory In Number Theory, we make the decision to work entirely with whole numbers. There are many reasons for this besides just mathematical interest, not the least of which is that

### SCHOOL OF ENGINEERING & BUILT ENVIRONMENT. Mathematics. Numbers

SCHOOL OF ENGINEERING & BUILT ENVIRONMENT Mathematics Numbers. Factors 2. Multiples 3. Prime and Composite Numbers 4. Modular Arithmetic 5. Boolean Algebra 6. Modulo 2 Matrix Arithmetic 7. Number Systems

### CS 101: Computer Programming and Utilizati on

CS 101: Computer Programming and Utilizati on Jul-Nov 2016 Bernard Menezes (cs101@cse.iitb.ac.in) Lecture 5: Conditional Execution About These Slides Based on Chapter 6 of the book An Introduction to Programming

### Discrete Mathematics Lecture 3 Elementary Number Theory and Methods of Proof. Harper Langston New York University

Discrete Mathematics Lecture 3 Elementary Number Theory and Methods of Proof Harper Langston New York University Proof and Counterexample Discovery and proof Even and odd numbers number n from Z is called

### CLASS 3, GIVEN ON 9/27/2010, FOR MATH 25, FALL 2010

CLASS 3, GIVEN ON 9/27/2010, FOR MATH 25, FALL 2010 1. Greatest common divisor Suppose a, b are two integers. If another integer d satisfies d a, d b, we call d a common divisor of a, b. Notice that as

### Chapter 3. if 2 a i then location: = i. Page 40

Chapter 3 1. Describe an algorithm that takes a list of n integers a 1,a 2,,a n and finds the number of integers each greater than five in the list. Ans: procedure greaterthanfive(a 1,,a n : integers)

### Math 319 Problem Set #3 Solution 21 February 2002

Math 319 Problem Set #3 Solution 21 February 2002 1. ( 2.1, problem 15) Find integers a 1, a 2, a 3, a 4, a 5 such that every integer x satisfies at least one of the congruences x a 1 (mod 2), x a 2 (mod

### Theorem (The division theorem) Suppose that a and b are integers with b > 0. There exist unique integers q and r so that. a = bq + r and 0 r < b.

Theorem (The division theorem) Suppose that a and b are integers with b > 0. There exist unique integers q and r so that a = bq + r and 0 r < b. We re dividing a by b: q is the quotient and r is the remainder,

### Engineering Problem Solving with C++, Etter/Ingber

Engineering Problem Solving with C++, Etter/Ingber Chapter 3 Control Structures 1 Control structures Algorithm Development Conditional Expressions Selection Statements Repetition Statements Structuring

### Chapter 6 Repetition

Chapter 6 Repetition 6-1 Repetition in C++ The final control/logic structure is repetition: Repetition repeating a block of code until a condition is met There are three repetition statements available

### Lecture 3: Finding integer solutions to systems of linear equations

Lecture 3: Finding integer solutions to systems of linear equations Algorithmic Number Theory (Fall 2014) Rutgers University Swastik Kopparty Scribe: Abhishek Bhrushundi 1 Overview The goal of this lecture

### Binary. ! You are probably familiar with decimal

Arithmetic operations in assembly language Prof. Gustavo Alonso Computer Science Department ETH Zürich alonso@inf.ethz.ch http://www.inf.ethz.ch/department/is/iks/ Binary! You are probably familiar with

### Elementary Number Theory We begin with a bit of elementary number theory, which is concerned

CONSTRUCTION OF THE FINITE FIELDS Z p S. R. DOTY Elementary Number Theory We begin with a bit of elementary number theory, which is concerned solely with questions about the set of integers Z = {0, ±1,

### The Laws of Cryptography Cryptographers Favorite Algorithms

2 The Laws of Cryptography Cryptographers Favorite Algorithms 2.1 The Extended Euclidean Algorithm. The previous section introduced the field known as the integers mod p, denoted or. Most of the field

### 1 Die hard, once and for all

ENGG 2440A: Discrete Mathematics for Engineers Lecture 4 The Chinese University of Hong Kong, Fall 2014 6 and 7 October 2014 Number theory is the branch of mathematics that studies properties of the integers.

### 4. Number Theory (Part 2)

4. Number Theory (Part 2) Terence Sim Mathematics is the queen of the sciences and number theory is the queen of mathematics. Reading Sections 4.8, 5.2 5.4 of Epp. Carl Friedrich Gauss, 1777 1855 4.3.

### cin >> num1 >> num2 >> num3 >> num4 >> num5; sum = num1 + num2 + num3 + num4 + num5; average = sum / 5.

Lesson Outcomes At the end of this chapter, student should be able to: Understand the requirement of a loop Understand the Loop Control Variable (LCV) Use increment (++) and decrement (--) operators Program

### Mathematics of Cryptography Modular Arithmetic, Congruence, and Matrices. A Biswas, IT, BESU SHIBPUR

Mathematics of Cryptography Modular Arithmetic, Congruence, and Matrices A Biswas, IT, BESU SHIBPUR McGraw-Hill The McGraw-Hill Companies, Inc., 2000 Set of Integers The set of integers, denoted by Z,

### a = bq + r where 0 r < b.

Lecture 5: Euclid s algorithm Introduction The fundamental arithmetic operations are addition, subtraction, multiplication and division. But there is a fifth operation which I would argue is just as fundamental

### The last three chapters introduced three major proof techniques: direct,

CHAPTER 7 Proving Non-Conditional Statements The last three chapters introduced three major proof techniques: direct, contrapositive and contradiction. These three techniques are used to prove statements

### Lecture 11: while loops CS1068+ Introductory Programming in Python. for loop revisited. while loop. Summary. Dr Kieran T. Herley 2016/17.

Lecture 11: while loops CS1068+ Introductory Programming in Python Dr Kieran T. Herley Python s while loop. Summary Department of Computer Science University College Cork 2016/17 KH (02/11/16) Lecture

### Control Structures in C++: Selection and Repetition Statements

Control Structures in C++: Selection and Repetition Statements 1. Log in to your account as usual and start up the Bloodshed Dev C/C++ System as described in Lab No. 1. Click on File New Source File. 2.

### Integer Factorization using the Quadratic Sieve

Integer Factorization using the Quadratic Sieve Chad Seibert* Division of Science and Mathematics University of Minnesota, Morris Morris, MN 56567 seib0060@morris.umn.edu March 16, 2011 Abstract We give

### The Prime Numbers. Definition. A prime number is a positive integer with exactly two positive divisors.

The Prime Numbers Before starting our study of primes, we record the following important lemma. Recall that integers a, b are said to be relatively prime if gcd(a, b) = 1. Lemma (Euclid s Lemma). If gcd(a,

### Python to C/C++ Fall 2011

Python to C/C++ Fall 2011 1. Main Program Python: Program code is indented after colon : def main(): body of program C/C++: Have more setup overhead. C: Both require #include directives to access libraries

### Branching. We ll continue to look at the basics of writing C++ programs including. Overview

Branching Overview We ll continue to look at the basics of writing C++ programs including Boolean Expressions (need to know this before we can using branching and looping!) Branching J.S. Bradbury CSCI

### 12 Greatest Common Divisors. The Euclidean Algorithm

Arkansas Tech University MATH 4033: Elementary Modern Algebra Dr. Marcel B. Finan 12 Greatest Common Divisors. The Euclidean Algorithm As mentioned at the end of the previous section, we would like to

### 9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

9 Control Statements 9.1 Introduction The normal flow of execution in a high level language is sequential, i.e., each statement is executed in the order of its appearance in the program. However, depending

### Section 4.2: The Division Algorithm and Greatest Common Divisors

Section 4.2: The Division Algorithm and Greatest Common Divisors The Division Algorithm The Division Algorithm is merely long division restated as an equation. For example, the division 29 r. 20 32 948

### 2 The Euclidean algorithm

2 The Euclidean algorithm Do you understand the number 5? 6? 7? At some point our level of comfort with individual numbers goes down as the numbers get large For some it may be at 43, for others, 4 In

### KENDRIYA VIDYALAYA TIRUMALAGIRI HOLIDAY HOMEWORK CLASS XII COMPUTER SCIENCE (083) C++ Practice Problems

(i).there are 39 problems. KENDRIYA VIDYALAYA TIRUMALAGIRI HOLIDAY HOMEWORK CLASS XII COMPUTER SCIENCE (083) C++ Practice Problems 1. What is the exact output of the program below? Indicate a blank space

### 4.2 The while Loop. ***Same as Fig 3.6 in intro5e p91

Chapter 4 Loops Objectives To use while, do-while, and for loop statements to control the repetition of statements ( 4.2-4.4). To understand the flow of control in loop statements ( 4.2-4.4). To use Boolean

### Continued fractions and good approximations.

Continued fractions and good approximations We will study how to find good approximations for important real life constants A good approximation must be both accurate and easy to use For instance, our

### GCDs and Relatively Prime Numbers! CSCI 2824, Fall 2014!

GCDs and Relatively Prime Numbers! CSCI 2824, Fall 2014!!! Challenge Problem 2 (Mastermind) due Fri. 9/26 Find a fourth guess whose scoring will allow you to determine the secret code (repetitions are

### 6. Control Structures

- 35 - Control Structures: 6. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may bifurcate, repeat code or take decisions. For that purpose,

### Informatica e Sistemi in Tempo Reale

Informatica e Sistemi in Tempo Reale Introduction to C programming Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 25, 2010 G. Lipari (Scuola Superiore Sant Anna)

### APPLICATIONS OF THE ORDER FUNCTION

APPLICATIONS OF THE ORDER FUNCTION LECTURE NOTES: MATH 432, CSUSM, SPRING 2009. PROF. WAYNE AITKEN In this lecture we will explore several applications of order functions including formulas for GCDs and

### Mathematics of Cryptography Part I

CHAPTER 2 Mathematics of Cryptography Part I (Solution to Odd-Numbered Problems) Review Questions 1. The set of integers is Z. It contains all integral numbers from negative infinity to positive infinity.

### MODULAR ARITHMETIC. a smallest member. It is equivalent to the Principle of Mathematical Induction.

MODULAR ARITHMETIC 1 Working With Integers The usual arithmetic operations of addition, subtraction and multiplication can be performed on integers, and the result is always another integer Division, on

### Unit 2: Number Systems, Codes and Logic Functions

Unit 2: Number Systems, Codes and Logic Functions Introduction A digital computer manipulates discrete elements of data and that these elements are represented in the binary forms. Operands used for calculations

### Intermediate Math Circles March 7, 2012 Linear Diophantine Equations II

Intermediate Math Circles March 7, 2012 Linear Diophantine Equations II Last week: How to find one solution to a linear Diophantine equation This week: How to find all solutions to a linear Diophantine

### Integer Multiplication and Division

6 Integer Multiplication and Division 6.1 Objectives After completing this lab, you will: Understand binary multiplication and division Understand the MIPS multiply and divide instructions Write MIPS programs

### Problem Set 5. AABB = 11k = (10 + 1)k = (10 + 1)XY Z = XY Z0 + XY Z XYZ0 + XYZ AABB

Problem Set 5 1. (a) Four-digit number S = aabb is a square. Find it; (hint: 11 is a factor of S) (b) If n is a sum of two square, so is 2n. (Frank) Solution: (a) Since (A + B) (A + B) = 0, and 11 0, 11

### Mathematics of Cryptography

CHAPTER 2 Mathematics of Cryptography Part I: Modular Arithmetic, Congruence, and Matrices Objectives This chapter is intended to prepare the reader for the next few chapters in cryptography. The chapter

### Final Exam Review. CS 1428 Fall Jill Seaman. Final Exam

Final Exam Review CS 1428 Fall 2011 Jill Seaman 1 Final Exam Friday, December 9, 11:00am to 1:30pm Derr 241 (here) Closed book, closed notes, clean desk Comprehensive (covers entire course) 25% of your

### Prime Numbers. Chapter Primes and Composites

Chapter 2 Prime Numbers The term factoring or factorization refers to the process of expressing an integer as the product of two or more integers in a nontrivial way, e.g., 42 = 6 7. Prime numbers are

### Lecture 13 - Basic Number Theory.

Lecture 13 - Basic Number Theory. Boaz Barak March 22, 2010 Divisibility and primes Unless mentioned otherwise throughout this lecture all numbers are non-negative integers. We say that A divides B, denoted

### CHAPTER 5. Number Theory. 1. Integers and Division. Discussion

CHAPTER 5 Number Theory 1. Integers and Division 1.1. Divisibility. Definition 1.1.1. Given two integers a and b we say a divides b if there is an integer c such that b = ac. If a divides b, we write a

### Introduction to Programming (in C++) Sorting. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Introduction to Programming (in C++) Sorting Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC Sorting Let elem be a type with a operation, which is a total order A vector

### Algebra for Digital Communication

EPFL - Section de Mathématiques Algebra for Digital Communication Fall semester 2008 Solutions for exercise sheet 1 Exercise 1. i) We will do a proof by contradiction. Suppose 2 a 2 but 2 a. We will obtain

### RSA and Primality Testing

and Primality Testing Joan Boyar, IMADA, University of Southern Denmark Studieretningsprojekter 2010 1 / 81 Correctness of cryptography cryptography Introduction to number theory Correctness of with 2

### Factoring & Primality

Factoring & Primality Lecturer: Dimitris Papadopoulos In this lecture we will discuss the problem of integer factorization and primality testing, two problems that have been the focus of a great amount

### Lecture 8: Binary Multiplication & Division

Lecture 8: Binary Multiplication & Division Today s topics: Addition/Subtraction Multiplication Division Reminder: get started early on assignment 3 1 2 s Complement Signed Numbers two = 0 ten 0001 two

### Public Key Cryptography: RSA and Lots of Number Theory

Public Key Cryptography: RSA and Lots of Number Theory Public vs. Private-Key Cryptography We have just discussed traditional symmetric cryptography: Uses a single key shared between sender and receiver

### U.C. Berkeley CS276: Cryptography Handout 0.1 Luca Trevisan January, 2009. Notes on Algebra

U.C. Berkeley CS276: Cryptography Handout 0.1 Luca Trevisan January, 2009 Notes on Algebra These notes contain as little theory as possible, and most results are stated without proof. Any introductory

### Induction. Mathematical Induction. Induction. Induction. Induction. Induction. 29 Sept 2015

Mathematical If we have a propositional function P(n), and we want to prove that P(n) is true for any natural number n, we do the following: Show that P(0) is true. (basis step) We could also start at

### 9. The Pails of Water Problem

9. The Pails of Water Problem You have a 5 and a 7 quart pail. How can you measure exactly 1 quart of water, by pouring water back and forth between the two pails? You are allowed to fill and empty each

### Further linear algebra. Chapter I. Integers.

Further linear algebra. Chapter I. Integers. Andrei Yafaev Number theory is the theory of Z = {0, ±1, ±2,...}. 1 Euclid s algorithm, Bézout s identity and the greatest common divisor. We say that a Z divides

### Solutions to Homework Set 3 (Solutions to Homework Problems from Chapter 2)

Solutions to Homework Set 3 (Solutions to Homework Problems from Chapter 2) Problems from 21 211 Prove that a b (mod n) if and only if a and b leave the same remainder when divided by n Proof Suppose a

### Greatest Common Divisor

Greatest Common Divisor Blake Thornton Much of this is due directly to Josh Zucker, Paul Zeitz and Harold Reiter. Divisibility 1. How can 48 be built from primes? In what sense is there only one way? How

### Congruences. Robert Friedman

Congruences Robert Friedman Definition of congruence mod n Congruences are a very handy way to work with the information of divisibility and remainders, and their use permeates number theory. Definition

### Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Motivation Suppose that we want a program that can read in a list of numbers and sort that list, or nd the largest value in that list. To be concrete about it, suppose we have 15 numbers to read in from

### Chapter 8 Selection 8-1

Chapter 8 Selection 8-1 Selection (Decision) The second control logic structure is selection: Selection Choosing between two or more alternative actions. Selection statements alter the sequential flow

### While Loop. 6. Iteration

While Loop 1 Loop - a control structure that causes a set of statements to be executed repeatedly, (reiterated). While statement - most versatile type of loop in C++ false while boolean expression true

### Number Theory. Proof. Suppose otherwise. Then there would be a finite number n of primes, which we may

Number Theory Divisibility and Primes Definition. If a and b are integers and there is some integer c such that a = b c, then we say that b divides a or is a factor or divisor of a and write b a. Definition

### An Efficient RNS to Binary Converter Using the Moduli Set {2n + 1, 2n, 2n 1}

An Efficient RNS to Binary Converter Using the oduli Set {n + 1, n, n 1} Kazeem Alagbe Gbolagade 1,, ember, IEEE and Sorin Dan Cotofana 1, Senior ember IEEE, 1. Computer Engineering Laboratory, Delft University

### Chapter 3: Elementary Number Theory and Methods of Proof. January 31, 2010

Chapter 3: Elementary Number Theory and Methods of Proof January 31, 2010 3.4 - Direct Proof and Counterexample IV: Division into Cases and the Quotient-Remainder Theorem Quotient-Remainder Theorem Given