0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Kotlinでべき乗(累乗)

Posted at

べき乗とは

同じ数を自身に何度も繰り返し掛け算する計算方法を「冪乗(べきじょう)」または「累乗(るいじょう)」といいます
冪乗は「an」のように表記し、「aをn回掛ける」という計算を表します。

pow

powはDouble型かFloat型を使う。

    val doubleX = 2.0
    val doubleY = 3.0
    val result = doubleX.pow(doubleY) 
    println(result) // 8.0

    val floatX = 2.0f
    val floatY = 3.0f
    val result = floatX.pow(floatY)
    println(result) // 8.0

Intをべき乗する際もtoDouble()でDouble型に変換しながらべき乗を行えば問題ない。

    val intX = 2
    val intY = 3
    val result = intX.toDouble().pow(intY).toInt()
    println(result) // 8

Mathクラスを使わない方法

fun main() {
    val intX = 2
    val intY = 3

    var result = 1
    for (i in 1..intY) {
       result *= intX
    }
    println(result) // Output: 8
}
0
0
0

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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?