in reply to Re^3: Avoid keeping larger lists in Memory
in thread Avoid keeping larger lists in Memory
Thank you Laurel for your suggestion on further Improving the code . I have tried the steps you have suggested partially (Still working on a sloution using the Square root of the target Number)
Here is my code and the O/p yields right results and execution time is higher compared to ur solution . I will think about adding the Square root portion and update this thread
#!/usr/bin/perl use warnings; use strict; ######## sub prime_factors { my $num = shift; my $large_prime_found = 2; my @primes = (); my $odd = 1; my $i = 0; for ( my $y = $large_prime_found; $y <= $num;) { $i++; #print "Iteration : $i, y => $y, Num => $num LP => $large_prime_f +ound, Arr Primes: @primes, Odd => $odd\n"; if ($num % 2 == 0) { $num /= $large_prime_found; $large_prime_found = 2; push @primes, $large_prime_found; next; } else { $odd += 2; #if ($odd <= sqrt($num)) { if ($num % $odd == 0 ) { $large_prime_found = $odd; $num /= $large_prime_found; push @primes, $large_prime_found; next; } #} } } return @primes; } $ time ./primes.pl Number: 20 , Prime_Factors: => 2 2 5 Number: 48 , Prime_Factors: => 2 2 2 2 3 Number: 96 , Prime_Factors: => 2 2 2 2 2 3 Number: 7 , Prime_Factors: => 7 Number: 69 , Prime_Factors: => 3 23 Number: 33 , Prime_Factors: => 3 11 Number: 13195 , Prime_Factors: => 5 7 13 29 Number: 600851475143 , Prime_Factors: => 71 839 1471 6857 real 0m0.011s user 0m0.005s sys 0m0.004s
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: Avoid keeping larger lists in Memory
by Laurent_R (Canon) on Jul 04, 2017 at 19:14 UTC | |
by pryrt (Abbot) on Jul 04, 2017 at 21:03 UTC | |
by Laurent_R (Canon) on Jul 04, 2017 at 21:33 UTC | |
by pr33 (Scribe) on Jul 05, 2017 at 04:29 UTC | |
by Laurent_R (Canon) on Jul 05, 2017 at 06:25 UTC | |
by pryrt (Abbot) on Jul 05, 2017 at 14:12 UTC | |
|