Recursive vs. Iterative Algorithm – Q&A

Question 1[2 marks]
For this question, we are looking at an algorithm used to implement the divisibility rule for 3 which states that:

A number is divisible by 3 if the sum of all its digits is divisible by 3.

Let’s look at the following example: is 378 divisible by 3? divisibility-rule-for-3 Here is the Python code for our recursive algorithm:
def isDivisibleByThree(n):
   sum = 0
   for digit in str(n):
     sum = sum + int(digit)
   
   if sum>=10:
     return isDivisibleByThree(sum)
   else:   
     if sum==3 or sum==6 or sum==9:
       return True
     else:
       return False
       
number = int(input("Type a number"))
if isDivisibleByThree(number)==True:
  print("This number is divisible by 3.")
else: 
  print("This number is not divisible by 3.")
Explain why the above code can be described as being a recursive algorithm? State on which line of this code does the recursion occur?
Question 2[4 marks]
Trace this algorithm if the user enters the value 8479
Question 3[4 marks]
Rewrite the function isDivisibleByThree() using an iterative approach instead of a recursive approach.
Save / Share Answers as a link
unlock-access

Solution...

The solution for this challenge is available to full members!
Find out how to become a member:
➤ Members' Area

Did you like this challenge?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 9

No votes so far! Be the first to rate this post.

As you found this challenge interesting...

Follow us on social media!

Tagged with: