Unit 171 Algorithms and Problem Solving - II Algorithm Efficiency Primality Testing Improved Primality Testing Sieve of Eratosthenes Primality Testing.

Slides:



Advertisements
Similar presentations
Sorting algorithms Sieve of Eratosthenes
Advertisements

Problem Solving 5 Using Java API for Searching and Sorting Applications ICS-201 Introduction to Computing II Semester 071.
Copyright © Cengage Learning. All rights reserved.
1 Chapter Six Algorithms. 2 Algorithms An algorithm is an abstract strategy for solving a problem and is often expressed in English A function is the.
Introduction to Computing Science and Programming I
Algorithms and Problem Solving
Computability and Complexity
Mathematical. Approach  Many of these problems read as brain teasers at first, but can be worked through in a logical way.  Just remember to rely on.
Copyright © 2013, 2010, and 2007, Pearson Education, Inc.
Chapter 9: Searching, Sorting, and Algorithm Analysis
Introduction to working with Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Computers and Programming.
1 Repetition structures Overview while statement for statement do while statement.
Unit 181 Recursion Definition Recursive Methods Example 1 How does Recursion work? Example 2 Problems with Recursion Infinite Recursion Exercises.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Unit 191 Recursion General Algorithm for Recursion When to use and not use Recursion Recursion Removal Examples Comparison of the Iterative and Recursive.
1 Recursion Overview l Introduction to recursion and recursive methods l Simple popular recursive algorithms l Writing recursive methods l Preview: 1-D.
Slides prepared by Rose Williams, Binghamton University Chapter 11 Recursion.
Review of Recursion What is a Recursive Method? The need for Auxiliary (or Helper) Methods How Recursive Methods work Tracing of Recursive Methods.
1 Repetition structures [cont’d] Overview l Nested Loops l Sentinel-Controlled loop l Avoiding Number Format exception.
More on Recursion Averting Program Crashes CSC 1401: Introduction to Programming with Java Week 9 – Lecture 3 Wanda M. Kunkle.
Writing algorithms using the for-statement. Programming example 1: find all divisors of a number We have seen a program using a while-statement to solve.
Chapter Number Theory 4 4 Copyright © 2013, 2010, and 2007, Pearson Education, Inc.
CS1101: Programming Methodology Aaron Tan.
Introduction Dr. Ying Lu RAIK 283: Data Structures & Algorithms.
Department of Computer Engineering Recursive Problem Solving Computer Programming for International Engineers.
Chapter 2 The Fundamentals: Algorithms, the Integers, and Matrices
MATH 224 – Discrete Mathematics
Recursion.
Iteration. Adding CDs to Vic Stack In many of the programs you write, you would like to have a CD on the stack before the program runs. To do this, you.
Chapter 12Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 12 l Basics of Recursion l Programming with Recursion Recursion.
 The pool rack example could be implemented using a for loop.  It is also possible to write recursive methods that accomplish things that you might.
CPSC 490 Number Theory Primes, Factoring and Euler Phi-function Mar.31 st, 2006 Sam Chan.
The Complexity of Primality Testing. What is Primality Testing? Testing whether an integer is prime or not. – An integer p is prime if the only integers.
Prime numbers Jordi Cortadella Department of Computer Science.
Lecturer: Dr. AJ Bieszczad Chapter 11 COMP 150: Introduction to Object-Oriented Programming 11-1 l Basics of Recursion l Programming with Recursion Recursion.
Introduction Algorithms and Conventions The design and analysis of algorithms is the core subject matter of Computer Science. Given a problem, we want.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
LAB#7. Insertion sort In the outer for loop, out starts at 1 and moves right. It marks the leftmost unsorted data. In the inner while loop, in starts.
5.1 Divisibility. Natural Numbers The set of natural numbers or counting numbers is {1,2,3,4,5,6,…}
Our Lesson: Review of factors Confidential.
Multidimensional Arrays. 2 Two Dimensional Arrays Two dimensional arrays. n Table of grades for each student on various exams. n Table of data for each.
Solving Problems Quickly UAkron Programming Team January 20, 2012.
Chapter 4: Control Structures II
Chapter 12. Recursion Basics of Recursion Programming with Recursion Computer Programming with JAVA.
Copyright © Cengage Learning. All rights reserved. 1.5 Prime Factorization.
Recursion A function that calls itself. Recursion A function which calls itself is said to be recursive. Recursion is a technique which will allow us.
CS 100Lecture 21 CS100J: Lecture 2 n Previous Lecture –Programming Concepts n problem, algorithm, program, computer, input, output, sequential execution,
UNIT-I INTRODUCTION ANALYSIS AND DESIGN OF ALGORITHMS CHAPTER 1:
Factors, Prime Numbers & Composite Numbers. Definition Product – An answer to a multiplication problem. 7 x 8 = 56 Product.
Chapter 11Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 11 l Basics of Recursion l Programming with Recursion Recursion.
Programming With Java ICS201 University Of Ha’il1 Chapter 11 Recursion.
Boolean expressions, part 1: Compare operators. Compare operators Compare operators compare 2 numerical values and return a Boolean (logical) value A.
Computer Science 320 A First Program in Parallel Java.
CSCI 125 & 161 Lecture 12 Martin van Bommel. Prime Numbers Prime number is one whose only divisors are the number 1 and itself Therefore, number is prime.
Chapter 4 With Question/Answer Animations 1. Chapter Summary Divisibility and Modular Arithmetic - Sec 4.1 – Lecture 16 Integer Representations and Algorithms.
General Condition Loop A general condition loop just loops while some condition remains true. Note that the body of the loop should (eventually) change.
Factors and Multiples.
Introduction to Search Algorithms
Copyright © 2016, 2013, and 2010, Pearson Education, Inc.
Sieve of Eratosthenes.
Sieve of Eratosthenes.
MODIFIED SIEVE OF ERATOSTHENES
AP Java Warm-up Boolean Array.
Basics of Recursion Programming with Recursion
Sieve of Eratosthenes The Sieve of Eratosthenes uses a bag to find all primes less than or equal to an integer value n. Begin by creating a bag an inserting.
Copyright © 2013, 2010, and 2007, Pearson Education, Inc.
Functions and Recursion
Introduction to Algorithms
From the last time: gcd(a, b) can be characterized in two different ways: It is the least positive value of ax + by where x and y range over integers.
Presentation transcript:

Unit 171 Algorithms and Problem Solving - II Algorithm Efficiency Primality Testing Improved Primality Testing Sieve of Eratosthenes Primality Testing - Applications Exercises

Unit 172 Algorithm Efficiency In the last unit we went through the definition and representation of an algorithm. The next question we face is: How to design an efficient algorithm for a given problem? Algorithm efficiency is concerned with utilization of two important resources –Time –Space Time complexity refers to the time taken by an algorithm to complete and produce a result. An improvement in time complexity increases the speed with which the algorithm proceeds to completion. Space complexity refers to the amount of space taken by an algorithm and produce a result. An improvement in space complexity reduces the amount of space (memory, disk space, etc.) taken by an algorithm.

Unit 173 Primality Testing To illustrate the concept of algorithm efficiency, we take up an important problem in computer science: Primality testing. An integer >= 2 is prime if and only if its only positive divisors are 1 and itself. The specific version of the problem which we refer to is as follows: Given a positive integer n find all primes less than or equal to n. A list of all prime integers less than or equal to 100 is given below:

Unit 174 Primality Testing – Algorithm Pseudocode Here is our algorithm in pseudocode: Given an integer n, for all positive integers k less than or equal to n do the following: 1.If k is prime, i.e. isPrime(k) is true, print k. Algorithm isPrime(int x) 1.For a given integer x do the following. 2.Assume that x is prime. 3.for all positive integers j less than x do the following 4.Divide x by j. If the remainder after division is equal to zero for any division, x is not prime. 5.Return the status of primality of x.

Unit 175 Example 1 import java.io.*; public class SimplePrimality { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter an integer: "); int limit = Integer.parseInt(in.readLine()); for(int count = 2; count <= limit; count++) if(isPrime(count)) System.out.print(count + "\t"); } public static boolean isPrime(int number) { int i = 2; while(i < number) {if(number % i == 0) return false; i++; } return true; }

Unit 176 Testing the Program Test the program for input = 100, 1000, 10000, , On a sample run, it was observed that the algorithm takes much longer to complete for larger inputs. This is because the algorithm tests for primality of a large integer n by repeated divisions for all integers from 2 to n – 1, which makes the algorithm take longer time to complete for large values of n. Is there any way we can improve this algorithm and make it faster?

Unit 177 Primality Testing - Improvements Observe that all prime numbers are odd, except for 2. Hence we do not need to divide a number with all even numbers. A division by 2 is enough to eliminate all even numbers. A second observation is that we do not need to divide an integer n by all integers upto n – 1 to check if it is prime or not. Instead we can test for primality only by dividing n by all odd integers from 3 to, to test for primality. To see this observe that if a divisor of n is greater that the corresponding divisor must be less than, since if both divisors are greater than, then their product will be greater than n, which is a contradiction. With these improvements the program becomes as follows:

Unit 178 Example 2 import java.io.*; public class FasterPrimality { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); System.out.println("Enter an integer: "); int limit = Integer.parseInt(in.readLine()); for(int count = 2; count <= limit; count++) if(isPrime(count)) System.out.print(count + "\t"); } public static boolean isPrime(int number) { boolean prime = true; if(number % 2 == 0 && number > 2) return false; int i = 3; int upper = ((int) Math.sqrt(number)); while(i <= upper) { if(number % i == 0) return false; i += 2; } return true; }

Unit 179 Testing the Program again Test the program for input = 100, 1000, 10000, , Observe the time taken by the program to complete. On a sample run, this program is much faster and efficient than the previous version, because the number of trial divisions has sharply reduced by more than half. Is there any way we can improve this algorithm further and make it even faster?

Unit 1710 Primality Testing – A Classic Algorithm The Sieve of Eratosthenes (276 BC BC). is a classic algorithm to find all primes between 1 and n. The algorithm is as follows: 1.Begin with an (unmarked) array of integers from 2 to n. 2.The first unmarked integer, 2, is the first prime. 3.Mark every multiple of this prime. 4.Repeatedly take the next unmarked integer as the next prime and repeat step 3. 5.Stop marking at multiples when the last unmarked multiple is greater than 6.After all markings are done, all unmarked integers are primes between 2 and n.

Unit 1711 Sieve of Eratosthenes - Example For example, our beginning array is: –(Unmarked) –(After step 1) –(After step 2) (All even multiples of 3 are already marked) –(After step 3) –The final list of primes is 2, 3, 7, 11, 13, 17,19. Note that this algorithm takes more space resources than either of the previous two algorithms. Is this algorithm more time efficient than the previous two algorithms?

Unit 1712 Primality Testing - Applications Primality Testing these days is used in computer security algorithms. Most notable of these is the RSA Algorithm which relies on the apparent difficulty of factoring a large integer. If you can find the factors of the following number you could win US$200,000!: Check for further details.

Unit 1713 Exercises 1.Can you convert both example 1 and example 2 to find and print all composite integers between 2 and n? Will it have any effect on the efficiency of the algorithm. Note that a composite integer is an integer that is not prime. 2.Implement the pseudocode for the Sieve of Eratosthenes Algorithm in Java. 3.Check the java library java.math. Is there a method for primality testing? (Hint: Look for the class BigInteger). How slow or fast is it as compared to our method isPrime(int x) in Example 2?