Euler Problem Number 1 in Scheme (Comparison with CL and Java)

I know the Euler project administrators try discourage to users from posting Euler solutions, but I hope there isn't any harm in posting an solution implementation for the first couple of problems. I plan on posting possible solutions in a variety of different programming languages. Here are three implementations in Scheme, Common Lisp and procedural Java.

;;
;; Euler problem, number 1
;; Environment: mzscheme
;;
;; If we list all the natural numbers below 10 that
;; are multiples of 3 or 5, we get 3, 5, 6 and 9.
;; The sum of these multiples is 23.
;;
;; Find the sum of all the multiples of 3 or 5 below 1000.
;;
;; References:
;; [1] http://schemecookbook.org/Cookbook/TOC
;;

(define (euler1 n)
(let ((x 0))
(do ([i 0 (+ i 1)]) [(= i n)]
(if (or (= 0 (modulo i 5))
(= 0 (modulo i 3)))
(begin
(set! x (+ x i)))))
x))

(define (main)
(display "Running\n")
(display (euler1 999))
(display "\nDone\n")
(exit))

(main)

Common Lisp

(loop for x from 3 to 999
when (or (zerop (mod x 3))
(zerop (mod x 5)))
sum x)

Java

public class euler1 {
public static int euler1(final int n) {
int sum = 0;
for (int i = 0; i < n; i++) {
if (((i % 3) == 0) || ((i % 5) == 0)) {
sum += i;
}
}
return sum;
}
public static void main(final String [] args) {
System.out.println("Running");
System.out.println("-->" + euler1(1000));
}
}

Comments

Popular posts from this blog

Is Java the new COBOL? Yes. What does that mean, exactly? (Part 1)

On Unit Testing, Java TDD for developers to write

JVM Notebook: Basic Clojure, Java and JVM Language performance