Last active
March 31, 2020 04:30
-
-
Save NouranMahmoud/7c9cb828c43287b9a74f0085242fcba9 to your computer and use it in GitHub Desktop.
Two ways with Two functions to calculate the GCF for (two numbers) only.
This file contains 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
/* | |
Greatest Common Factor | |
GCF function takes two numbers and generates the greatest common factor. | |
*/ | |
function GCF(num1, num2) { | |
var arr1 = findFactors(num1); | |
var arr2 = findFactors(num2); | |
var cf = []; // store common factors. | |
for (var i = 0; i < arr1.length; i ++) { | |
for (var y = 0; y < arr2.length; y++) { | |
// get the common factors (the number which exist on both arrays) | |
if (arr1[i] === arr2[y]) { | |
cf.push(arr1[i]); | |
} | |
} | |
} | |
//sort common factors and grap the first/largest one. | |
var gcf = cf.sort(function(a,b){a-b})[0]; | |
return gcf; | |
} | |
/* findFactors take a number to calculate its factors (Factors are the numbers you multiply together | |
to get another number:) | |
*/ | |
function findFactors(num) { | |
var arr = []; | |
// loop over the num to find all the numbers that accept to divide the (num). | |
for(var i = 1; i <= num; i++) { | |
if(num%i === 0 ) { // if remainder is 0, this means it accept dividing by this number | |
arr.push(i); // you can push (i) it is divisable by (num) | |
} | |
} | |
return arr; | |
} | |
function GCF2(num1, num2) { | |
var gcf = recursion(num1, num2); | |
return gcf; | |
} | |
function recursion(num1, num2) { | |
// the equation is num1 = Math.floor(num1/num2)*num2 + remainder; | |
// but I chanegd it to be able to store the remainder .. which will be our GCF. | |
var remainder = num1 - Math.floor(num1/num2)*num2; | |
// if remainder if 0, then we need the previous remainder which is num2 | |
if(remainder === 0) { | |
return num2; | |
} | |
num1 = num2; | |
num2 = remainder; | |
return recursion(num1, num2); // re calculate with the new values. | |
} | |
//geting the performance of each one, it seams that GCF2 is faster than GCF (and this is logical :D). | |
function GCF_perf(n,m){ | |
var t0 = performance.now(); | |
var result = GCF(n,m); | |
var t1 = performance.now(); | |
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result); | |
} | |
function GCF2_perf(n,m){ | |
var t0 = performance.now(); | |
var result = GCF2(n,m); | |
var t1 = performance.now(); | |
console.log('Took', (t1 - t0).toFixed(4), 'milliseconds to generate:', result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
too complicated