Home > Back-end >  Is it possible to add two numbers whose power is the iterator in for loop in Kotlin without using po
Is it possible to add two numbers whose power is the iterator in for loop in Kotlin without using po

Time:06-25

Programming Language: KOTLIN

I'm trying to make a function which adds two numbers in the following way.. a^i b^i where "i" would be the iterator in for loop. So I want the i to range from 1 to 10 and print the result one by one like this... for example if I give the values as a=1 & b=2 then the result must be calculated as.. a^1 b^1= 1^1 2^1 which gives 3 so print the result. a^2 b^2= 1^2 2^2 which gives 6 and print the result. etc., repeating the process until i becomes 10. so I tried the following code and it only prints the result of initial values.

fun main(){
    println(test(22,33))
}
fun test(a:Int,b:Int):Int{
    var result1=1
    var result2=1
    var result3=result1 result2
     for(i in 1..10){
         result1*=a
         result2*=b
         result3=a b
         println(result3)
         }
     return result3
   }

CodePudding user response:

In this line of your code:

result3 = a   b

you are not adding the result of a b to result3, you are assigning it. It should look like this:

result3  = a   b

Shorter version:

fun test(a: Int, b: Int): Int {
  var result = 0
  for (i in 1..10) {
    result  = i * (a   b)
  }
  return result
}

Shortest version:

fun test(a: Int, b: Int) = (1..10).sumOf { it * (a   b) }

CodePudding user response:

You were only adding the parameters of your function for result3. This works though:

fun addWithIteratedPower(a: Int, b: Int) : Int {
    var resultA = 1
    var resultB = 1
    var combinedResult = 0
    for(i in 1..10){
        resultA *= a
        resultB *= b
        combinedResult = resultA   resultB
        println(combinedResult)
    }
    return combinedResult
}

And here's a test that validates it:

@Test
fun `should return final combined result`(){
    val oneAndTwoToPowerOfTenAdded = (1.0.pow(10)   2.0.pow(10)).toInt()
    assertThat(addWithIteratedPower(1, 2)).isEqualTo(oneAndTwoToPowerOfTenAdded)
}
  • Related