Skip to content

Conversation

VeronicaM
Copy link
Owner

All PRs

  • I have self-reviewed my code
  • I have written tests which cover new and changed functionality
  • All tests pass
  • I have commented on difficult to understand code

Where Relevant

  • I have compared and validated my UI changes against the designs
  • I've updated relevant documentation e.g. README

Description

What is this PR about ?

Find the greatest common divisor of two given numbers

What was implemented ?

  1. Iterative solution
  • Loop from 1 to max, where max is num1 if num1 > num2, or num2 is num2 > num1
  • Check if num1 % i === 0 && num2 % i === 0
  • check if i is greater than a variable greatest divisor if yes replace it.

Runtime complexity: O(max)
Space complexity: O(1)

This could have been further optimised by

  • Using the min instead of max
  • looping in reverse from min to 1
  • breaking as soon as the condition num1 % i === 0 && num2 % i === 0 returns true
  • if no common divisor is found return -1
  1. Recursive solution
  • Base case:
    • num1 === 0 || num2 === 0
    • num1 === num2 return num1
  • recursive case calling the function again with the subtraction of the smaller number from the bigger one.

Runtime complexity and space complexity : O(max/min)

What did you learn ?

  • A problem can be written in many different ways, it's important to pay attention to how they compare in terms of performance to each other.
  • Taking advantage of math properties helps to simplify the algorithms and remove redundant steps.

What links/documents relate to this PR ?

Testing

Steps required to test

  • cd interviews/recursion/greatest-common-divisor
  • run node greatest-common-divisor.js

All tests should pass
Test cases can be found in interviews/recursion/greatest-common-divisor/testData

VeronicaM added 6 commits May 9, 2020 14:06
…ntime complexity, n = max(num1, num2), O(1) space complexity
…that makes use of the properties of division being written as subtraction of a number from the other. O(max - min) runtime and space complexity
@VeronicaM VeronicaM merged commit 1b85dcd into master May 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant