Home > Software engineering >  Kotlin - How to write Code to get "Sum of all divisors of an integer"
Kotlin - How to write Code to get "Sum of all divisors of an integer"

Time:01-26

Hallo, i am very new to Kotlin and one of my task is write a Code to get Sum of all divisors of an integer. Its doesnt matter which Interger to use. First Approach is with Imperativ Style and Second is with Collektion Function in functional Style.

I did write many Programm like Simple Banking, Sorted list or simple Elevator programm but that task confuse because i am not a Math Guy. My Idea is to creat a value like "2" and make some divisior in a For loop or like that.

Hope i dont sound like a Stupid Guy.

Hope you can help me.

Thx for your Effort and Time. Live Long and Prosper

CodePudding user response:

// Imperative

val number = 100

var divisorSum = 0
for (i in 1..number) {
  if (number % i == 0) {
    // divisorSum  = (number / i)
    // or shorter – see @Tenfour04's comment:
    divisorSum  = i
  }
}

println(divisorSum)


// Functional

val number = 100

val result = (1..number)
  .filter { number % it == 0 }
  // .sumOf { number / it }
  // or shorter – see @Tenfour04's comment:
  .sum()

println(result)
  •  Tags:  
  • Related