#!/usr/bin/ruby

#
## http://rosettacode.org/wiki/Sailors,_coconuts_and_a_monkey_problem
#

func coconuts(sailors, monkeys=1) {
    if ((sailors < 2) || (monkeys < 1) || (sailors <= monkeys)) {
        return 0
    }
    var blue_cocos = sailors-1
    var pow_bc = blue_cocos**sailors
    var x_cocos = pow_bc
    while ((x_cocos-blue_cocos)%sailors || ((x_cocos-blue_cocos)/sailors < 1)) {
        x_cocos += pow_bc
    }
    return monkeys*(x_cocos / pow_bc * sailors**sailors - blue_cocos)
}

2.to(9).each { |sailor|
    say "#{sailor}: #{coconuts(sailor)}";
}
