Skip to content

Instantly share code, notes, and snippets.

@teacons
Created October 2, 2021 15:00
Show Gist options
  • Save teacons/d7d777776fdddf98e004c3c295252a5e to your computer and use it in GitHub Desktop.
Save teacons/d7d777776fdddf98e004c3c295252a5e to your computer and use it in GitHub Desktop.
package ru.fbear.arithmetic
import kotlin.math.abs
fun main(args: Array<String>) {
println("Hello World!")
// Try adding program arguments at Run/Debug configuration
println("Program arguments: ${args.joinToString()}")
}
class Arithmetic {
/**
* Subtracting [b] from [a]
* @return Subtraction result.
*/
fun subtraction(a: Int, b: Int): Int = a + negatate(b)
/**
* Multiply [a] by [b]
* @return Result of multiplication.
*/
fun multiply(a: Int, b: Int): Int {
var sum = 0
for (i in 1..abs(b))
sum += a
if (b < 0)
sum = negatate(sum)
return sum
}
/**
* Dividing [a] by [b]
* @return Division Result.
*/
fun division(a: Int, b: Int): Int {
if (b == 0) throw IllegalArgumentException("b cannot be 0")
var dividend = abs(a)
val divider = abs(b)
var result = 0
while (dividend >= divider) {
dividend -= divider
result++
}
return if ((a < 0 && b < 0) || (a > 0 && b > 0)) result
else negatate(result)
}
private fun negatate(a: Int): Int {
var num = a
var negative = 0
val x = if (a < 0) 1 else -1
while (num != 0) {
negative += x
num += x
}
return negative
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment