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



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

8 Primes and Modular Arithmetic

The Euclidean Algorithm

Elementary Number Theory and Methods of Proof. CSE 215, Foundations of Computer Science Stony Brook University

Today s Topics. Primes & Greatest Common Divisors

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

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

CS 103X: Discrete Structures Homework Assignment 3 Solutions

8 Divisibility and prime numbers

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

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

Homework until Test #2

CSI 333 Lecture 1 Number Systems

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

Factoring Algorithms

Lecture 3: Finding integer solutions to systems of linear equations

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

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

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

Math 319 Problem Set #3 Solution 21 February 2002

6. Control Structures

Section 4.2: The Division Algorithm and Greatest Common Divisors

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

Integer Factorization using the Quadratic Sieve

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

Informatica e Sistemi in Tempo Reale

Intermediate Math Circles March 7, 2012 Linear Diophantine Equations II

Lecture 13 - Basic Number Theory.

Factoring & Primality

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

Chapter 8 Selection 8-1

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

Public Key Cryptography: RSA and Lots of Number Theory

Binary Number System. 16. Binary Numbers. Base 10 digits: Base 2 digits: 0 1

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

PIC 10A. Lecture 7: Graphics II and intro to the if statement

RSA and Primality Testing

While Loop. 6. Iteration

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

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

Lecture 8: Binary Multiplication & Division

Unit 6. Loop statements

MATH 289 PROBLEM SET 4: NUMBER THEORY

DIVISIBILITY AND GREATEST COMMON DIVISORS

Discrete Mathematics, Chapter 4: Number Theory and Cryptography

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

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

Common Beginner C++ Programming Mistakes

Basics of I/O Streams and File I/O

The While Loop. Objectives. Textbook. WHILE Loops

Grade 7/8 Math Circles Fall 2012 Factors and Primes

J a v a Quiz (Unit 3, Test 0 Practice)

Test1. Due Friday, March 13, 2015.

Number Representation

Keywords are identifiers having predefined meanings in C programming language. The list of keywords used in standard C are : unsigned void

Base Conversion written by Cathy Saxton

Computer and Network Security

13 Classes & Objects with Constructors/Destructors

Compiler Construction

Functions Recursion. C++ functions. Declare/prototype. Define. Call. int myfunction (int ); int myfunction (int x){ int y = x*x; return y; }

Cryptography and Network Security Number Theory

Section IV.1: Recursive Algorithms and Recursion Trees

COMPUTER SCIENCE 1999 (Delhi Board)

of Nebraska - Lincoln

Handout NUMBER THEORY

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

Continued Fractions and the Euclidean Algorithm

Breaking The Code. Ryan Lowe. Ryan Lowe is currently a Ball State senior with a double major in Computer Science and Mathematics and

To convert an arbitrary power of 2 into its English equivalent, remember the rules of exponential arithmetic:

Statements and Control Flow

Just the Factors, Ma am

Lecture 2 Notes: Flow of Control

Practice Questions. CS161 Computer Security, Fall 2008

Primes in Sequences. Lee 1. By: Jae Young Lee. Project for MA 341 (Number Theory) Boston University Summer Term I 2009 Instructor: Kalin Kostadinov

Numeral Systems. The number twenty-five can be represented in many ways: Decimal system (base 10): 25 Roman numerals:

CS 241 Data Organization Coding Standards

Lecture Notes on Linear Search

MATH10040 Chapter 2: Prime and relatively prime numbers

Elementary Number Theory

Grade 6 Math Circles. Binary and Beyond

A Study on the Necessary Conditions for Odd Perfect Numbers

THE NUMBER OF REPRESENTATIONS OF n OF THE FORM n = x 2 2 y, x > 0, y 0

Settling a Question about Pythagorean Triples

SUBGROUPS OF CYCLIC GROUPS. 1. Introduction In a group G, we denote the (cyclic) group of powers of some g G by

Translating to Java. Translation. Input. Many Level Translations. read, get, input, ask, request. Requirements Design Algorithm Java Machine Language

15 Prime and Composite Numbers

COMPSCI 210. Binary Fractions. Agenda & Reading

ALGORITHMS AND FLOWCHARTS

F ahrenheit = 9 Celsius + 32

Binary Division. Decimal Division. Hardware for Binary Division. Simple 16-bit Divider Circuit

Positional Numbering System

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

a 11 x 1 + a 12 x a 1n x n = b 1 a 21 x 1 + a 22 x a 2n x n = b 2.

Some facts about polynomials modulo m (Full proof of the Fingerprinting Theorem)

Sources: On the Web: Slides will be available on:

Passing 1D arrays to functions.

Regression Verification: Status Report

Number Theory: A Mathemythical Approach. Student Resources. Printed Version

Transcription:

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à, Fernando Orejas Dept. of Computer Science, UPC This specification suggests some algorithm with a repetitive procedure. Syntax: The while statement 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 2 Write the numbers 1 N // Input: read a number N > 0 // Output: write the numbers 1...N (one per line) 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 3 Introduction to Programming Dept. CS, UPC 4

Product of two numbers A quick algorithm for the product //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 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; 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: 17 38 = 646 x y p 17 38 34 19 34 18 34 68 9 68 8 68 136 4 272 2 544 1 544 0 544 646 Introduction to Programming Dept. CS, UPC 5 A quick algorithm for the product Introduction to Programming Dept. CS, UPC 6 Why is the quick product interesting? 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 17 38 0 34 19 0 34 18 34 68 9 34 68 8 102 136 4 102 272 2 102 544 1 102 544 0 646 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 7 Introduction to Programming Dept. CS, UPC 8

Quick product in binary: example Counting a s 77 x 41 = 3157 1001101 x 0101001 ------- 1001101 1001101 1001101 ------------ 110001010101 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 9 Counting a s // Input: sequence of characters that ends with. // Output: number of times a appears in the // sequence 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 10 Counting digits We want to read a non-negative integer and count the number of digits (in radix 10) in its textual representation. Examples 8713105 7 digits 156 3 digits 8 1 digit 0 1 digit (note this special case) Introduction to Programming Dept. CS, UPC 11 Introduction to Programming Dept. CS, UPC 12

Counting digits Euclid s algorithm for gcd // Input: a non-negative number N // Output: number of digits in N (0 has 1 digit) 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; Properties gcd(a,a)=a If a > b, then gcd(a,b) = gcd(a-b,b) Example a b 114 42 72 42 30 42 30 12 18 12 6 12 6 6 gcd (114, 42) Introduction to Programming Dept. CS, UPC 13 Euclid s algorithm for gcd // Input: read two positive numbers (a and b) // Output: write gcd(a,b) 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 14 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 114 42 42 30 30 12 12 6 6 0 Introduction to Programming Dept. CS, UPC 15 Introduction to Programming Dept. CS, UPC 16

Faster Euclid s algorithm for gcd // Input: read two positive numbers (a and b) // Output: write gcd(a,b) 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; 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 17 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 12 56 4 30 30 30 1024 896 128 100 99 1 17 51 17 Introduction to Programming Dept. CS, UPC 18 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 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 19 Introduction to Programming Dept. CS, UPC 20

Solving a problem several times Prime number // Input: several pairs of natural numbers at the input // Output: the gcd of each pair of numbers written at the output 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; 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 21 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 N; cin >> N; Introduction to Programming Dept. CS, UPC 22 Prime number Observation: as soon as a divisor is found, there is no need to check divisibility with the rest of the divisors. 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; 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 23 Introduction to Programming Dept. CS, UPC 24

Prime number 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 N; cin >> N; If N is not prime, we can find two numbers, a and b, such that: N = a b, with 1 < a b <N int divisor = 2; bool is_prime = (N!= 1); and with the following property: a N 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; 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 25 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 Introduction to Programming Dept. CS, UPC 26 Iterations Is there any real difference? 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; Number of bits Introduction to Programming Dept. CS, UPC 27 Introduction to Programming Dept. CS, UPC 28

In real time (N= 2110454939) The for statement > time prime_slow < number is prime 10.984u 0.004s 0:11.10 98.9% > time prime_fast < number is prime 0.004u 0.000s 0:00.00 0.0% 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 29 In general The for statement 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 30 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 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 31 Introduction to Programming Dept. CS, UPC 32

Calculate x y Drawing a triangle // Input: read two integer numbers, x and y, such that y >= 0 // Output: write x y int x, y; cin >> x >> y; int p = 1; for (int i = 0; i < y; ++i) p = p x; cout << p << endl; Given a number n (e.g. n = 6), we want to draw this triangle: * ** *** **** ***** ****** Introduction to Programming Dept. CS, UPC 33 Drawing a triangle // Input: read a number n > 0 // Output: write a triangle of size n Introduction to Programming Dept. CS, UPC 34 Perfect numbers A number n > 0 is perfect if it is equal to the sum of all its divisors except itself. 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; Examples 6 is a perfect number (1+2+3 = 6) 12 is not a perfect number (1+2+3+4+6 12) Strategy Keep adding divisors until the sum exceeds the number or there are no more divisors. Introduction to Programming Dept. CS, UPC 35 Introduction to Programming Dept. CS, UPC 36

Perfect numbers Perfect numbers // Input: read a number n > 0 // Output: write a message indicating // whether it is perfect or not int n; cin >> n; Would the program work using the following loop condition? while (d <= n/2 and sum < 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; 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 37 Introduction to Programming Dept. CS, UPC 38