0

# Could someone explain why this algorithim does what it does...

First thing's first, here's the C++ and the Ruby algorithim... https://code.sololearn.com/c1CJuGxUdRxe https://code.sololearn.com/cKlxwgWJN34d i understand the inner loop: the index is being divided by that at number and the number is being added to the array or printed as many times as possible, so long as the remainder is 0, but what about the outer loop? what's happening there, with number/index ?

2 Réponses

+ 3

Given you don't understand what you have written, I'm guessing you got the code from someplace else. If that is true, you are required by SoloLearn to document where or who for any public codes.
The outer loop test is meant to pick the prime numbers to check. It checks everything whether it is prime or not. However, since the prime is found first, it doesn't matter that 4 is tested as it won't work after all of the 2 factors are removed.

+ 2

Both programs have a bug. Enter 9 to the c++ code and you'll see it's problem. For the Ruby, change a primeFactors call to use a prime number like 7.
C++ line 44 needs a if (number > 1) to skip the output of 1. 9 /= 3 is 3 and 3 /= 3 is 1. The number should be considered gone at this point.
Ruby line 23 needs a:
if number > 1
arr << number
so the prime is added.