Created
December 19, 2015 01:11
-
-
Save jinwolf/52b38fd446bba2cf72ae to your computer and use it in GitHub Desktop.
Unique combination of factors
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
| /* | |
| PrintFactors(12) | |
| 12 * 1 | |
| 6 * 2 // 2 * 6 ( 2 * 2 * 3) | |
| 4 * 3 | |
| 3 * 2 * 2 ( 3 * 4) | |
| PrintFactors(32) | |
| 32 * 1 | |
| 16 * 2 | |
| 8 * 4 | |
| 8 * 2 * 2 | |
| 4 * 4 * 2 | |
| 4 * 2 * 2 * 2 | |
| 2 * 2 * 2 * 2 * 2 | |
| PrintFactors(12) = 12 * PrintFactors(1) | |
| PrintFactors(12) = 3 * PrintFactors(4) | |
| PrintFactors(4) = 2 * PrintFactors(2) | |
| var stack = []; | |
| PrintFactors(2) | |
| 2 * 1* 1 | |
| PrintFactors(1) | |
| 1 * 1 | |
| */ | |
| function factors(n) { | |
| // n = 12, | |
| var stack = []; | |
| console.log(n + ' * 1'); | |
| printFactors(n, n / 2, stack); | |
| } | |
| function printFactors(n, largestFactor, stack) { | |
| if (n === 1) { | |
| console.log(stack.join(' * ')); | |
| return; | |
| } | |
| for (var i = largestFactor; i > 1; --i) { | |
| if (n % i === 0) { | |
| stack.push(i); | |
| printFactors(n / i, i , stack); | |
| stack.pop(i); | |
| } | |
| } | |
| } | |
| factors(1); | |
| factors(2); | |
| factors(32); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment