in reply to Nested loops

You've been given the answer to your question about $c not being defined, as well as additional material on why this does not happen with $a and $b. I will not comment further on that.

In my humble opinion, your algorithm is quite poor. The simple fact that, when given a third number to check, you need to add another nested loops, shows that this is not quite right.

You need an algorithm that will still work without any code change even if we add one, two or more numbers to the list of divisors to check.

You could use two different routes.

One is to loop on your range of integers and, for each of them, check if it is a multiple of the numbers stored in @s, and to store it in a @result array (or to print it out) it it is not a multiple of any of the @s numbers.

The other one would be to calculate all the multiples of the numbers in @s that are smaller than your upper bound, store them in a hash, and grep on that hash the full range.

Update: A short one-liner test showing the second option above (a variation on the sieve of Eratosthenes algorithm for prime numbers):

$ perl -e 'my @lines = (1..2310) ; my @s = (13, 17); my %multiples; > for my $div (@s) { > $multiples{$_ * $div} = 1 for 1..200; > } > my @result = grep {not exists $multiples{$_} } @lines; > print "@result"; > ' 1 2 3 4 5 6 7 8 9 10 11 12 14 15 16 18 19 20 21 22 23 24 25 27 28 29 3 +0 31 32 33 35 36 37 38 40 41 42 43 44 45 46 47 48 49 50 53 54 55 56 5 +7 58 59 60 61 62 63 64 66 67 69 70 71 72 73 74 75 76 77 79 80 81 82 8 +3 84 86 87 88 89 90 92 93 ... 2299 2300 2302 2303 2304 2305 2306 2307 2308 2309 2310

Replies are listed 'Best First'.
Re^2: Nested loops
by robert44444uk (Acolyte) on Sep 14, 2015 at 21:42 UTC

    Thank you all for your contributions and thank you Laurent_R for your improved code

      Hi robert44444uk,

      Just to further add to what the Monks above have imparted - ever heard of recursion?

      #! perl -slw use strict; sub count_id (\@\@); # "count indivisible dividends" fnc prototype sub count_id (\@\@) { my ($divisors,$range) = (shift,shift); return 0 unless @$range && @$divisors; # check terminal condition # apply the $divisors to the dividend for this recursive call my ($aggregate,$dividend) = (0,pop @$range); for (@$divisors) { return count_id(@$divisors,@$range) if !($divid +end % $_); } return 1 + count_id(@$divisors,@$range); } my @divisors = (13,17,19); my @range = (1..2310); print "Number of indivisible items: ",count_id(@divisors,@range),"\n"; __END__

        Thank you Shadowsong, this is also a very useful piece of code, and I will play with it for sure, when I get the chance.