DNHI Homework 2 Solutions Recursion

Similar documents
Mathematical Background

CS-140 Fall 2017 Test 1 Version Practice Practice for Nov. 20, Name:

CS 61B Asymptotic Analysis Fall 2017

Mini models EECS /74

Elementary Sorts 1 / 18

CSE 311: Foundations of Computing. Lecture 10: Set Operations & Representation, Modular Arithmetic

CSCI-141 Exam 1 Review September 19, 2015 Presented by the RIT Computer Science Community

Introduction to Algorithmic Complexity. D. Thiebaut CSC212 Fall 2014

CSE 311: Foundations of Computing. Lecture 26: Cardinality

CSE 311: Foundations of Computing. Lecture 10: Set Operations & Representation, Modular Arithmetic

CSE 311 Lecture 11: Modular Arithmetic. Emina Torlak and Kevin Zatloukal

1.00 Lecture 31. Systems of Linear Equations

Tou has been released!

public void run ( ) { i f ( this. id == 0) System. out. p r i n t ( 3 ) ; bro. j o i n ( ) ; else System. out. p r i n t ( 2 ) ;

CSE 311: Foundations of Computing. Lecture 10: Set Operations & Representation, Modular Arithmetic

More About Methods. Hsuan-Tien Lin. Deptartment of CSIE, NTU. OOP Class, March 8-9, 2010

Chapter 4 Number Representations

Introduction to Computing II (ITI 1121) FINAL EXAMINATION

Problem Decomposition: One Professor s Approach to Coding

CSE 20 DISCRETE MATH. Fall

A Study on the Minimum and Maximum Sum of C2 Problem in IMO2014

Lecture 5: Sep. 23 &25

CMPSCI 250: Introduction to Computation. Lecture #15: The Fundamental Theorem of Arithmetic David Mix Barrington 24 February 2014

Fall 2017 November 10, Written Homework 5

3.3 Accumulation Sequences

CMSC 132, Object-Oriented Programming II Summer Lecture 10:

CSEN202: Introduction to Computer Programming Spring Semester 2014 Final Exam

Solutions to Assignment 1

Introduction to Programming (Java) 3/12

II. BASIC THEORIES A. System of Rigid Body I. INTRODUCTION. B. Decrease and Conquer

Chapter 4. A simple method for solving first order equations numerically

CS-140 Fall 2018 Test 2 Version Practice Nov. 12, 2018

Analysis of Algorithms

Fibonacci (Leonardo Pisano) ? Statue in Pisa Italy FIBONACCI NUMBERS AND RECURRENCES

Lecture 8: ES 102 Functions, Searching and Sorting

Carleton University. Final Examination Fall DURATION: 2 HOURS No. of students: 223

Introduction to Computer Programming, Spring Term 2018 Practice Assignment 5 Discussion: power(m,n) = m n

2011 Hypatia Contest

Übung Informatik I - Programmierung - Blatt 7

CS 2336 Discrete Mathematics

CSE 311: Foundations of Computing. Lecture 27: Undecidability

CMSC 132, Object-Oriented Programming II Summer Lecture 1:

9.6 r-combinations with Repetition Allowed

In Exercises 1 12, list the all of the elements of the given set. 2. The set of all positive integers whose square roots are less than or equal to 3

New Bohr model calculates Helium ground state energy correctly

Basic Java OOP 10/12/2015. Department of Computer Science & Information Engineering. National Taiwan University

Lecture 14: Nov. 11 & 13

DM507 - Algoritmer og Datastrukturer Project 1

Intermediate Math Circles February 14, 2018 Contest Prep: Number Theory

CS Exam 1 Study Guide and Practice Exam

Motivation. Dictionaries. Direct Addressing. CSE 680 Prof. Roger Crawfis

CS 163/164 - Exam 1 Study Guide and Practice Exam

Determining an Optimal Parenthesization of a Matrix Chain Product using Dynamic Programming

6.001 SICP September? Procedural abstraction example: sqrt (define try (lambda (guess x) (if (good-enuf? guess x) guess (try (improve guess x) x))))

Homework 3: Solutions

On my honor, as an Aggie, I have neither given nor received unauthorized aid on this academic work

CS-140 Fall 2018 Test 2 Version Practice Nov. 12, Name:

Lecture 7 Feb 4, 14. Sections 1.7 and 1.8 Some problems from Sec 1.8

The Sommerfeld Polynomial Method: Harmonic Oscillator Example

Recurrence Relations and Recursion: MATH 180

1 Trees. Listing 1: Node with two child reference. public class ptwochildnode { protected Object data ; protected ptwochildnode l e f t, r i g h t ;

Discovering Spam On Twitter

Keywords: input, systems, subset sum problem, algorithm, P NP, the proof of x ± y = b. GJRE-I Classification : FOR Code:

Functional Big-step Semantics

CMSC 132, Object-Oriented Programming II Summer Lecture 11:

Solution suggestions for examination of Logic, Algorithms and Data Structures,

cse 311: foundations of computing Fall 2015 Lecture 12: Primes, GCD, applications

Take-home Lab 1. Arrays

MADHAVA MATHEMATICS COMPETITION, December 2015 Solutions and Scheme of Marking

Richard Gibson CSC 421 Assignment #4 Apr. 4, 2006 #

Recursive Definitions

Outline. 1 Merging. 2 Merge Sort. 3 Complexity of Sorting. 4 Merge Sort and Other Sorts 2 / 10

Examples of Unlimited Register Machine programs for Turingcomputable

Problem One: Order Relations i. What three properties does a binary relation have to have to be a partial order?

RMT 2014 Power Round Solutions February 15, 2014

MCS 260 Exam 2 13 November In order to get full credit, you need to show your work.

The Quantum Harmonic Oscillator

CMSC 132, Object-Oriented Programming II Summer Lecture 6:

Introduction to Induction (LAMC, 10/14/07)

Topic Contents. Factoring Methods. Unit 3: Factoring Methods. Finding the square root of a number

Problem Set 5 Solutions

Functions in Python L435/L555. Dept. of Linguistics, Indiana University Fall Functions in Python. Functions.

Solutions to Practice Final

Fall 2017 Test II review problems

Math 261 Final Exam - Practice Problem Solutions. 1. A function f is graphed below.

Section Summary. Sequences. Recurrence Relations. Summations. Examples: Geometric Progression, Arithmetic Progression. Example: Fibonacci Sequence

CS325: Analysis of Algorithms, Fall Final Exam

Review problems solutions

#A67 INTEGERS 18 (2018) ON THE NESTED LOCAL POSTAGE STAMP PROBLEM

Review. Principles of Programming Languages. Equality. The Diamond Property. The Church-Rosser Theorem. Corollaries. CSE 230: Winter 2007

CMSC 132, Object-Oriented Programming II Summer Lecture 12

NOTE: You have 2 hours, please plan your time. Problems are not ordered by difficulty.


Meta-programming & you

JUST THE MATHS UNIT NUMBER 1.4. ALGEBRA 4 (Logarithms) A.J.Hobson

Mathematical Induction. How does discrete math help us. How does discrete math help (CS160)? How does discrete math help (CS161)?

SEQUENCES, MATHEMATICAL INDUCTION, AND RECURSION

Carleton University. Final Examination Fall DURATION: 2 HOURS No. of students: 275

Plan for Today and Beginning Next week (Lexical Analysis)

Binomial Coefficient Identities/Complements

Transcription:

Solutions Recursion Problem 1 Part A Write an iterative method that computes a value of x n for a positive integer n and a real number x. The return value of -1 indicates an error condition. 1 public static double poweriter (double x, int n) { double result = 1; 3 4 if (n < 0 ) return -1; 5 6 while (n > 0) { 7 result = result * x; 8 n--; 9 10 return result; 11 Write a recursive method that computes a value of x n for a positive integer n and a real number x. The return value of -1 indicates an error condition. X 1 public static double powerrecursive (double x, int n) { 3 if (n < 0 ) return -1; 4 if (n == 0) return 1; 5 return x * powerrecursive (x, n - 1); Problem Consider the following recursive method 1 public int recmethod ( int number ) { if ( number <= 0 ) 3 return 0; 4 if ( number % == 0 ) 5 return recmethod ( number - 1 ); 6 else 7 return number + recmethod ( number - 1); 9 Part A How many times is this method called (including the initial call) when we run recmethod(10)? Called 11 times. How many times is this method called (including the initial call) when we run recmethod(-10)? Called 1 time. 1

What does recmethod do (i.e. what does it compute)? It computes the sum of odd numbers from zero to number. Problem 3 Write a recursive method to compute the following series: 1 3 + 5 + 3 7 + 4 9 +... + i i + 1. The crucial part in this code is casting to double so that the fractions do not become all zero. Other than that it should be a straight forward implementation of the recursive method. 1 public static double summation ( int num ) { // b a s e c a s e 3 if ( num <= 0 ) return 0; 4 // r e c u r s i o n 5 return (double)num/(*num+1) + summation(num-1); Problem 4 Write a recursive method that computes the sum of the digits in an integer. Use the following method header: public static int sumofdigits ( long n ) For example, sumofdigits( 34 ) should return 9 (since + 3 + 4 = 9 ) and sumofdigits( 390 ) should return 1 (since 3 + 9 + 0 = 1 ). A possible solution could be: 1 public static int sumofdigits ( long n ) { // b a s e c a s e is w h e n t h e n u m b e r is z e r o 3 if( n==0 ) 4 return 0; 5 // r e c u r s i v e c a s e 6 return ( (int)(n%10) + sumofdigits( n/10 ) ); 7 Problem 5 For each of the following recursive methods, rewrite it using iterations instead of recursion. HINT: in order to do so you should first figure out what these methods do. Part A public int recur( int n ) { if (n < 0 ) throw new IllegalArgumentException ("negative argument detected"); return recur_proper(n); public int recur_proper ( int n ) { if (n < 0 ) return -1; else if ( n < 10 )

return 1; else return ( 1 + recur_proper ( n / 10 ) ); The code above computes the number of digits in the parameter n. 1 public int recur (int n) { if (n < 0 ) throw new IllegalArgumentException ("negative argument detected"); 3 if (n == 0 ) return 1; 4 int solution = 0; 5 while (n > 0 ){ 6 solution++; 7 n = n/10; 9 return solution; 10 public int recur ( int n ){ if (n < 0 ) return -1; else if ( n < 10 ) return n; else return ( n % 10 + recur ( n / 10 ) ); This method computes sum of digits in a parameter n. 1 public int recur ( int n ){ int sum = 0; 3 while (n > 0 ) { 4 sum += n%10; 5 n = n/10; 7 return sum; Problem 6 What would be printed by the following programs Part A) 1 public class CatsAndDogs { 3 public static void main(string[] args) { 4 foo("", 4); 5 6 7 public static void foo ( String s, int n ) { 8 if (n <= 1) 9 System.out.println("Cats"); 10 else { 3

11 System.out.println( s ) ; 1 foo ( s, n-1 ); 13 14 15 Cats ) 1 public class Numbers { 3 public static void main(string[] args) { 4 int [] list = {1,, 3, 4, 5; 5 System.out.println( foo (list, 0, list.length-1) ); 7 8 public static int foo ( int [] nums, int begin, int end ) { 9 if ( begin == end ) 10 return nums[begin]; 11 else 1 return nums[begin] + foo(nums, begin+1, end); 13 14 The foo method computes the sum of the values in the list from between index begin and index end. So in this case it computes the sum of all elements in the list. It prints 15 Problem 7 Part A Write a method that generates all sequences of a given length that contain digits 0 through 9 (all ten digits are allowed, repetitions are allowed)? Given length of the sequence equal to n, how many possible sequences are there? With length of n digits, the number of possible sequences is equal to 10 n, for example, with lenght of n = 4, we have 10, 000 different sequences. 1 /* * * G e n e r a t e a l l d e c i m a l s e q u e n c e s of t h e s p e c i f i e d l e n g t h. 3 * @ p a r a m l e n g t h t h e l e n g t h of t h e s e q u e n c e s to be g e n e r a t e d 4 */ 5 public static void getalldecimalsequences ( int length ) { 6 String seq = new String () ; 7 getalldecimalsequences( length, seq); 9 10 /* G e n e r a t e a l l d e c i m a l s e q u e n c e s of a s p e c i f i e d l e n g t h 11 * u s i n g t h e s e q S t r i n g as s t o r a g e f o r p a r t i a l s e q u e n c e s. 1 * @ p a r a m l e n g t h t h e l e n g t h of t h e s e q u e n c e to be g e n e r a t e d 13 * @ p a r a m s e q s t o r e s p a r t i a l s e q u e n c e s b e t w e e n r e c u r s i v e c a l l s 14 */ 15 private static void getalldecimalsequences ( int length, String seq ) { 16 if (seq.length() == length ) {// r e a c h e d t h e d e s i r e d l e n g t h 17 System.out.printf("%s %n", seq ); 1 4

19 else { // a d d t h e n e x t d i g i t to t h e s e q u e n c e ( t w o p o s s i b i l i t i e s ) 0 1 for (int i = 0; i < 10; i++) { // a d d d i g i t i to t h e c u r r e n t s e q u e n c e 3 getalldecimalsequences( length, seq + Integer.toString(i)); 4 5 digits? Modify the above method so that none of the generated sequences start with zero. How many of those sequences exist, given the length of n With this restriction, we only have 9 possiblities for the first digit and 10 for all the remaining digits. So there will be total of 9 10 n 1 sequences of length n that do not start with a zero. 1 /* * * G e n e r a t e a l l d e c i m a l s e q u e n c e s of t h e s p e c i f i e d l e n g t h w i t h a d d e d 3 * c o n s t r a i n t t h a t t h e f i r s t d i g i t is n e v e r z e r o. 4 * @ p a r a m l e n g t h t h e l e n g t h of t h e s e q u e n c e s to be g e n e r a t e d 5 */ 6 public static void getdecimalsequencesnoleadingzero ( int length ) { 7 String seq = new String () ; 8 getdecimalsequencesnoleadingzero( length, seq); 9 10 11 /* 1 * G e n e r a t e a l l d e c i m a l s e q u e n c e s of t h e s p e c i f i e d l e n g t h w i t h a d d e d 13 * c o n s t r a i n t t h a t t h e f i r s t d i g i t is n e v e r z e r o. s e q is u s e d f o r s t o r a g e 14 * of p a r t i a l s e q u e n c e s. 15 * @ p a r a m l e n g t h t h e l e n g t h of t h e s e q u e n c e s to be g e n e r a t e d 16 * @ p a r a m s e q s t o r e s p a r t i a l s e q u e n c e s b e t w e e n r e c u r s i v e c a l l s 17 */ 18 private static void getdecimalsequencesnoleadingzero ( int length, String seq ) { 19 if (seq.length() == length ) {// r e a c h e d t h e d e s i r e d l e n g t h 0 System.out.printf("%s %n", seq ); 1 else if (seq.length() == 0 ) { // do n o t s t a r t a n y s e q u e n c e w i t h a z e r o 3 for (int i = 1; i < 10; i++) { 4 // a d d d i g i t i to t h e c u r r e n t s e q u e n c e 5 getdecimalsequencesnoleadingzero( length, seq + Integer.toString(i)); 7 8 else { 9 for (int i = 0; i < 10; i++) { 30 // a d d d i g i t i to t h e c u r r e n t s e q u e n c e 31 getdecimalsequencesnoleadingzero( length, seq + Integer.toString(i)); 3 33 34 5