Let us take a very common example of a program that determines the prime factors of a large number say 10^9 order. The way to overcome the problem of memory leakage is to use an algorithm that does not require to loop through the end of the number to find the prime factors.
Algorithm: The function primeFactors() accepts an argument num which is the original number to be factorized. An empty array is declared which will store the prime factors. The outer for loop loops from i=2 till i=sqrt(num). If the number is divided by the current value of i, the current value of i is pushed into the array. Since we are only concerned with finding distinct prime factors we push the factor into the array first and then keep dividing the number by i until it is no longer divisible and then it breaks the while loop with a reduced value for num. The for loop completes and the final value of num is checked. If the value of num is greater than 2 then it is the largest prime factor and is pushed into the array.
[ 23719, 41843 ]
- Prime array is declared
- for loop runs from i=2 to i=31503
- i=23719 divides num with rem=0 and 23719 is also a prime number,
hence it is pushed into the array.
- num/i = 41843 thus num= 41843, is also a prime number which is not divisible by any number
within the range of i
- num>2 and is the largest prime factor hence it is pushed into the array.
[ 2, 5 ]
- num=1000000000000000000 is an even number and is divisible by 2.
- 2 is pushed into the array and we keep dividing the current value of num by 2 until it is no longer divisible.
- Looping through the range of i, the next prime number is 5 which is pushed into the array.
- After the completion of the for loop num=0 and all the prime factors have been stored.