Skip to content

Instantly share code, notes, and snippets.

@178inaba
Last active August 29, 2015 14:20
Show Gist options
  • Save 178inaba/b5b5cfa8750a0a557c50 to your computer and use it in GitHub Desktop.
Save 178inaba/b5b5cfa8750a0a557c50 to your computer and use it in GitHub Desktop.
hello worldより「コラッツの問題」書くほうがいろいろ学べそう ref: http://qiita.com/inaba178/items/9dc2026780ca7d148b26
library collatz;
collatz(int n) {
print(n.toString());
if (n > 1) {
if (n % 2 == 1) {
collatz(3 * n + 1);
} else {
collatz((n / 2).round());
}
}
}
package main
import (
"flag"
"fmt"
"time"
)
func main() {
n := flag.Uint64("n", 1, "collatz start num")
flag.Parse()
num := *n
if num < 1 {
fmt.Println("Invalid value:", num)
return
}
collatz(num)
}
func collatz(num uint64) {
fmt.Println(num)
time.Sleep(time.Second / 2)
if num%2 == 1 && num > 1 {
collatz(3*num + 1)
} else if num%2 == 0 {
collatz(num / 2)
}
}
#!/bin/sh
collatz() {
n=$1
echo $n
sleep 0.5s
if [ `echo "$n % 2" | bc` -eq 1 ] && [ $n != "1" ]; then
collatz `echo "3 * $n + 1" | bc`
elif [ `echo $n % 2 | bc` -eq 0 ]; then
collatz `echo $n / 2 | bc`
fi
}
collatz $1
package main
import (
"flag"
"fmt"
"os"
"time"
)
var isSleep bool
func main() {
n := flag.Uint64("n", 1, "collatz target num. infinite loop if it was the this flag is 1 and l flag is true.")
l := flag.Bool("l", false, "loop from 1 to the target. infinite loop if it was the this flag is true and n flag is 1.")
s := flag.Bool("s", false, "0.5 seconds sleep every calculation.")
flag.Parse()
num := *n
isSleep = *s
loop := *l
if num < 1 {
fmt.Println("invalid value:", num)
os.Exit(1)
}
if loop {
if num == 1 {
for i := uint64(1); ; i++ {
loopCollatz(i)
}
} else {
for i := uint64(1); i <= num; i++ {
loopCollatz(i)
}
}
} else {
ret := collatz(num)
retCheck(ret)
}
}
func loopCollatz(i uint64) {
ret := collatz(i)
fmt.Println("----------")
retCheck(ret)
}
func collatz(num uint64) (ret uint64) {
fmt.Println(num)
if isSleep {
time.Sleep(time.Second / 2)
}
if num > 1 {
if num%2 == 1 {
ret = collatz(3*num + 1)
} else if num%2 == 0 {
ret = collatz(num / 2)
}
} else {
ret = num
}
return
}
func retCheck(ret uint64) {
if ret != 1 {
fmt.Println("invalid collatz return:", ret)
os.Exit(1)
}
}
def collatz(n)
show n
if n.odd? and n > 1
collatz(3n + 1)
else if n.even?
collatz(n / 2)
import 'package:collatz/collatz.dart' as collatz;
import 'package:args/args.dart';
import 'dart:io';
main(List<String> arguments) {
final parser = new ArgParser()..addOption('num', defaultsTo: '1', abbr: 'n');
ArgResults arg = parser.parse(arguments);
int num = int.parse(arg['num']);
if (num < 1) {
print('invalid value:' + arg['num']);
exit(1);
}
collatz.collatz(num);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment