050 Consecutive prime sum -- v2.pl 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. #!/usr/bin/perl
  2. # Daniel "Trizen" Șuteu
  3. # Date: 25 July 2021
  4. # https://github.com/trizen
  5. # Which prime, below one-million, can be written as the sum of the most consecutive primes?
  6. # https://projecteuler.net/problem=50
  7. # Runtime: 0.033s
  8. use 5.020;
  9. use strict;
  10. use warnings;
  11. use ntheory qw(:all);
  12. use experimental qw(signatures);
  13. sub p50($limit) {
  14. my @prime_sum = (0);
  15. for (my $p = 2 ; ; $p = next_prime($p)) {
  16. my $sum = $prime_sum[-1] + $p;
  17. last if ($sum >= $limit);
  18. push @prime_sum, $sum;
  19. }
  20. my $terms = 1;
  21. my $max_prime = 2;
  22. my $start_p_index = 1;
  23. foreach my $i (0 .. $#prime_sum) {
  24. for (my $j = $#prime_sum ; $j >= $i + $terms ; --$j) {
  25. my $n = $prime_sum[$j] - $prime_sum[$i];
  26. if (($j - $i > $terms or $n > $max_prime) and $n < $limit and is_prime($n)) {
  27. ($terms, $max_prime, $start_p_index) = ($j - $i, $n, $i + 1);
  28. last;
  29. }
  30. }
  31. }
  32. say "$max_prime is the sum of $terms consecutive primes with first prime = ", nth_prime($start_p_index);
  33. }
  34. p50(1e6);