LoginSignup
4
4

More than 5 years have passed since last update.

2016で遊ぶ

Last updated at Posted at 2016-01-07

のtweetを見て、Swiftでも試してみた。

累乗計算用の演算子を定義。
(負の数を考慮していないなど、簡易版です)

infix operator ** {
associativity left
}

public func ** (lhs: Int, rhs: Int) -> Int {
    if lhs <= 0 { return 1 }
    return (1..<rhs).reduce(lhs) { (acc, _) -> Int in acc * lhs }
}

試す

// 2016 = 1+2+3+4+...+63
(1...63).reduce(0, combine: +) //=> 2016

// 2016 = 2⁵+2⁶+2⁷+2⁸+2⁹+2¹⁰
(5...10).map({ 2 ** $0 }).reduce(0, combine: +) //=> 2016

// 2016 = 3³+4³+5³+6³+7³+8³+9³
(3...9).map({ $0 ** 3 }).reduce(0, combine: +) //=> 2016

2016という数値は面白いですね。
(2016は完全数ではない.. フィボナッチ数ではない.. 素数ではない..)

4
4
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4