Aistis Raulinaitis
Aistis Raulinaitis

Reputation: 85

Summing very large numbers in Racket

So I am looking to sum up the numbers between zero and one hundred million. This code works extremely well for ten million, executing on my machine in about 3 seconds. However as soon as I attempt to sum up to one hundred million, it freezes my computer along with never finishing. I have waited for this code to finish for five minutes and yet it still will not finish.

#lang racket/base

(require (only-in racket/list range))

(let ([theList (range 0 100000000)]) (time (apply + theList)))

Upvotes: 2

Views: 322

Answers (2)

Greg Hendershott
Greg Hendershott

Reputation: 16260

You can use for/sum:

(for/sum ([i (in-range 100000000)])
  i)

Like all of the for/xxx variations, for/sum is essentially implemented in terms of for/fold (which Chris Jester-Young explained). In other words for/sum is a convenience wrapper around for/fold.

Upvotes: 6

C. K. Young
C. K. Young

Reputation: 223133

The standard way to sum numbers in Racket, to my knowledge, is to use for/fold rather than apply, if your range is huge:

(for/fold ((n 0))
          ((i (in-range 100000000)))
  (+ n i))

This takes half a second to run on my computer.

Upvotes: 4

Related Questions