5.1 KiB
5.1 KiB
euler-problem-1
euler-problem-1
Here is my solution to the Project Euler problem #1 in as many languages as I could write it.
Each section will first show the commands to run the program and then the source for it.
I should still add:
- C# (Mono)
Maybe, someday soon I'll also add:
- Ruby
- Io
- Prolog
- Scala
- Erlang
- Haskell
Bash
./euler-problem-1.sh
#!/bin/sh
TOTAL=0
I=0
while [ $I -lt 1000 ]; do
if [ $[ $I % 3 ] -eq 0 -o $[ $I % 5 ] -eq 0 ]; then
let TOTAL=TOTAL+I
fi
let I=I+1
done
echo $TOTAL
C
gcc euler-problem-1.c && ./a.out
#include <stdio.h>
int main(int argc, char *argv[])
{
int i, total = 0;
for (i = 0; i < 1000; i++)
if (i % 3 == 0 || i % 5 == 0)
total += i;
printf("%d\n", total);
return 0;
}
Clojure
clj euler-problem-1.clj
(def total 0)
(dotimes [i 1000]
(when (or (zero? (mod i 3)) (zero? (mod i 5)))
(def total (+ total i))))
(println total)
Emacs lisp
emacs -script euler-problem-1.el
(let ((i 0)
(total 0))
(while (< i 1000)
(when (or (zerop (mod i 3)) (zerop (mod i 5)))
(setq total (+ total i)))
(setq i (1+ i)))
(message "%d" total))
Go
go run euler-problem-1.go
package main
import (
"fmt"
)
func main() {
total := 0
for i := 0; i < 1000; i++ {
if i % 3 == 0 || i % 5 == 0 {
total += i
}
}
fmt.Printf("%d\n", total)
}
Java
javac euler-problem-1.java && java Problem
class Problem
{
public static void main(String args[])
{
int total = 0;
int i;
for (i = 0; i < 1000; i++)
if (i % 3 == 0 || i % 5 == 0)
total += i;
System.out.println(total);
}
}
JavaScript
js euler-problem-1.js
var total = 0;
for (i = 0; i < 1000; i++)
if (i % 3 == 0 || i % 5 == 0)
total += i;
print(total);
Common Lisp
sbcl --script euler-problem-1.lisp
(loop for i from 0 to 999
when (or (zerop (mod i 3)) (zerop (mod i 5))) sum i into total
finally (format t "~d~%" total))
PHP
php euler-problem-1.php
<?php
$total = 0;
for ($i = 0; $i < 1000; $i++)
if ($i % 3 == 0 || $i % 5 == 0)
$total += $i;
echo $total . "\n";
?>
Python
python euler-problem-1.py
TOTAL = 0
for i in range(1000):
if i % 3 == 0 or i % 5 == 0:
TOTAL += i
print(TOTAL)
Rep
rep euler-problem-1.java
(do ((i 0 (1+ i))
(total 0))
((>= i 1000)
(format standard-output "%d\n" total))
(when (or (zerop (mod i 3)) (zerop (mod i 5)))
(setq total (+ total i))))
Rust
rustc euler-problem-1.rs && ./euler-problem-1
fn main() {
let mut total = 0;
let mut i = 0;
while i < 1000 {
if i % 3 == 0 || i % 5 == 0 {
total += i;
}
i += 1;
}
io::print(fmt!("%d\n", total));
}
Scheme
guile euler-problem-1.scm
(use-modules ((rnrs base)))
(do ((i 0 (1+ i))
(total 0))
((>= i 1000)
(display total)
(newline))
(when (or (zero? (mod i 3)) (zero? (mod i 5)))
(set! total (+ total i))))
Vala
valac euler-problem-1.vala && ./euler-problem-1
class Euler.Problem1 : GLib.Object {
public static int main(string[] args) {
int total = 0;
for (int i = 0; i < 1000; i++)
if (i % 3 == 0 || i % 5 == 0)
total += i;
stdout.printf("%d\n", total);
return 0;
}
}