Last active
          October 24, 2017 07:54 
        
      - 
      
- 
        Save farskid/5ab17033e757b4e7a2b45db24f70d6c8 to your computer and use it in GitHub Desktop. 
    Find the Greatest Common Divisor of two numbers
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function gcd(n, m) { | |
| if (!m) { return n; } | |
| return (m, n % m); | |
| } | |
| console.log(gcd(512, 1024)); // 256 | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | function isEven(num) { | |
| return num % 2 === 0; | |
| } | |
| function findDevisors(num) { | |
| var result = [], max = isEven(num) ? num / 2 : Math.floor(num / 2); | |
| for (var i = 2; i <= max; i++) { | |
| if (num % i === 0) { | |
| result.push(i); | |
| } | |
| } | |
| return result; | |
| } | |
| function commonTwoArrays(a, b) { | |
| var result = []; | |
| a.forEach(function(item) { | |
| if (b.indexOf(item) !== -1) { | |
| result.push(item); | |
| } | |
| }); | |
| return result; | |
| } | |
| function gcd(n, m) { | |
| var nList = findDevisors(n); | |
| var mList = findDevisors(m); | |
| var commonList = commonTwoArrays(nList, mList); | |
| return Math.max.apply(null, commonList); | |
| } | |
| console.log(gcd(512, 1024)); // 256 | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment