Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over BigInteger values using foreach in Kotlin

Tags:

kotlin

I am trying to loop over BigInteger values in Kotlin using the following code snippet. But it's telling For-loop range must have an 'iterator()' method. How can I loop over the BigInteger values in Kotlin?

private fun pow(base: BigInteger, power: BigInteger): String {
        for(i in BigInteger.ZERO..power){ //Giving error

        }
    }
like image 409
sagar suri Avatar asked Dec 18 '22 17:12

sagar suri


1 Answers

You can extend BigInteger to allow this

In particular we need to:

  1. introduce rangeTo function to BigInteger (to allow using .. operator)
  2. add iterator function to the range returned by rangeTo operator

The rangeTo function

Here I'm defining an extension function for BigInteger

operator fun BigInteger.rangeTo(other: BigInteger) = 
        BigIntegerRange(this, other)

BigIntegerRange:

class BigIntegerRange(
        override val start: BigInteger,
        override val endInclusive: BigInteger
) : ClosedRange<BigInteger>, Iterable<BigInteger> {
    override operator fun iterator(): Iterator<BigInteger> =
            BigIntegerRangeIterator(this)
}

BigIntegerRangeIterator:

class BigIntegerRangeIterator(
        private val range: ClosedRange<BigInteger>
) : Iterator<BigInteger> {
    private var current = range.start

    override fun hasNext(): Boolean =
            current <= range.endInclusive

    override fun next(): BigInteger {
        if (!hasNext()) {
            throw NoSuchElementException()
        }
        return current++
    }
}

Now this code:

fun main() {
    for (i in BigInteger.ZERO..BigInteger.TEN) {
        println(i)
    }
}

Compiles and prints:

0
1
2
3
4
5
6
7
8
9
10

Do not forget to import the rangeTo function

See also:

  • Ranges
  • Control Flow. For Loops
like image 66
Denis Zavedeev Avatar answered Jan 05 '23 10:01

Denis Zavedeev