Reputation: 363
I was going over some problems for my discrete math class, and read an exercise that caught my attention (note: this is not homework. I'm just purely curious).
Question: How many times is the "print" statement executed for the following program segment? (i, j, k, m are integers):
for i := 1 to 20 do
for j := 1 to i do
for k := 1 to j do
for m := 1 to k do
print (i * j) + (k * m)
I tried to do it in python, but it was boring because I got it done in a few seconds. So for fun I tried to do it with DrRacket using scheme as the language. However, after reading documentation on loops, I can't seem to find reference for loops of this kind. So, using this specific example (or I guess a general one with an indefinite number of loops), how can this problem be solved?
Upvotes: 1
Views: 655
Reputation: 235984
A loop like this:
for i := 1 to 20 do
for j := 1 to i do
print [i, j]
Is equivalent to this in Racket, assuming that a loop range that looks like this: 1 to 20
includes all the numbers from 1 up to (and including) 20.
#lang racket
(for* ((i (in-range 1 21))
(j (in-range 1 (add1 i))))
(displayln (list i j)))
Notice that the above is not limited to one nested loop, you can declare as many nested loops and iteration variables as needed.
Upvotes: 6
Reputation: 71070
MIT Scheme:
(do ((cnt 0) (i 1 (+ i 1))) ((> i 20) cnt)
(do ((j 1 (+ 1 j))) ((> j i))
(do ((k 1 (+ 1 k))) ((> k j))
(do ((m 1 (+ 1 m))) ((> m k))
(set! cnt (+ 1 cnt))))))
;Value: 8855
But this is really a math problem, not a programming problem.
Upvotes: 0