in reply to Re: Avoid keeping larger lists in Memory
in thread Avoid keeping larger lists in Memory
Thanks Laurent and Thanks to all the Monks for the replies . Haukex's and Cristoforo's solution was very fast .
I have tried with division by 2 and only odd numbers in is_prime sub routine and that helped a lot in improving the execution time in finding whether a given number is prime or not
Cristofor's solution will generate a list of all prime factor's and then use that list to get the largest prime factor
#!/usr/bin/perl use strict; use warnings; ## my $max = 0; sub prime_factors { my $x = shift; my @factors; for ( my $y = 2; $y <= $x; $y++ ) { next if $x % $y; $x /= $y; push @factors, $y; redo; } return @factors; } foreach my $num (20,13195,600851475143) { my @factors = prime_factors( $num ); foreach my $p (@factors) { if ($p > $max) { $max = $p; } } print "Number: $num Largest Prime Factor: $max\n"; } -bash-4.1$ time ./large_prime.pl Number: 20 Largest Prime Factor: 5 Number: 13195 Largest Prime Factor: 29 Number: 600851475143 Largest Prime Factor: 6857 real 0m0.004s user 0m0.002s sys 0m0.002s
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Avoid keeping larger lists in Memory
by Laurent_R (Canon) on Jul 02, 2017 at 09:28 UTC | |
by pr33 (Scribe) on Jul 04, 2017 at 17:21 UTC | |
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 | |
|