Consider the following pseudocode for a reduce-and-conquer recursive SumDigit(num) algorithm that finds the sum of all d

Business, Finance, Economics, Accounting, Operations Management, Computer Science, Electrical Engineering, Mechanical Engineering, Civil Engineering, Chemical Engineering, Algebra, Precalculus, Statistics and Probabilty, Advanced Math, Physics, Chemistry, Biology, Nursing, Psychology, Certifications, Tests, Prep, and more.
Post Reply
answerhappygod
Site Admin
Posts: 899603
Joined: Mon Aug 02, 2021 8:13 am

Consider the following pseudocode for a reduce-and-conquer recursive SumDigit(num) algorithm that finds the sum of all d

Post by answerhappygod »

Consider the following pseudocode for areduce-and-conquer recursive SumDigit(num) algorithm that finds thesum of all digits in a number. Example calling SumDigit(1936)should return 19 (which is 6 + 3 + 9 +1)
integer SumDigit (num)
input: an integer number, num
output: sum of all the digits in num
if num is a one-digit number //base case
- then the sum of all the digits in num is, num
// example if num=7, then SumDigit(num), should return 7
otherwise //general case: num has multiple digits in it
- break num into 2 parts
- One part, part 1, has the rightmost digit (use modulo operation to dothat). Ex. 1936 % 10 -> 6
- The other part, part 2, has all the digits of num,except the rightmost digit. (use regular division to do this.Ex. 1936 / 10 -> 193
- Call the function SumDigit() itself on part 2, and getthe result of the sum of all the digits in part 2..
- Add the result from SumDigit(part 2) to part 1, and returnit
a. Write the corresponding C++ or Python code for thepseudocode. Submit only the code for the function
SumDigit() and not the whole program.
b. Using the modulo operation “%”, addition operation “+”, and division operation “/” as basic
operations, set up and solve a recurrence relation for the number of basic operations the algorithm
executes.
c. Modify the code to create a new recursive functionCountDigits(num) that counts the number of digits
in a number num. Example: a call to the functionCountDigits(1587) would return the value 4. Submit
only the code for the function CountDigits(num).
d. Using the modulo operation “%”, addition operation “+”, and division operation “/” as basic
operations, set up and solve a recurrence relation for thenumber of basic operations for
CountDigits(num).
Join a community of subject matter experts. Register for FREE to view solutions, replies, and use search function. Request answer by replying!
Post Reply