Arithmetic/Integer: Difference between revisions

Content added Content deleted
(→‎{{header|Ruby}}: added divmod)
(→‎{{header|Kotlin}}: Removed error handling (as specified by the task) and made the code use the Kotlin standard library instead of the Java standard library.)
Line 2,816: Line 2,816:


=={{header|Kotlin}}==
=={{header|Kotlin}}==
<syntaxhighlight lang="scala">// version 1.1
<syntaxhighlight lang="kotlin">
import kotlin.math.pow // not an operator but in the standard library


fun main(args: Array<String>) {
fun main() {
val r = Regex("""-?\d+[ ]+-?\d+""")
val r = Regex("""-?[0-9]+\s+-?[0-9]+""")
print("Enter two integers separated by space(s): ")
while(true) {
val input: String = readLine()!!.trim()
print("Enter two integers separated by space(s) or q to quit: ")
val input: String = readLine()!!.trim()
val index = input.lastIndexOf(' ')
val a = input.substring(0, index).trimEnd().toLong()
if (input == "q" || input == "Q") break
if (!input.matches(r)) {
val b = input.substring(index + 1).toLong()
println("$a + $b = ${a + b}")
println("Invalid input, try again")
continue
println("$a - $b = ${a - b}")
}
println("$a * $b = ${a * b}")
println("$a / $b = ${a / b}") // rounds towards zero
val index = input.lastIndexOf(' ')
println("$a % $b = ${a % b}") // if non-zero, matches sign of first operand
val a = input.substring(0, index).trimEnd().toLong()
val b = input.substring(index + 1).toLong()
println("$a ^ $b = ${a.toDouble().pow(b.toDouble())}")
}
println("$a + $b = ${a + b}")
println("$a - $b = ${a - b}")
println("$a * $b = ${a * b}")
if (b != 0L) {
println("$a / $b = ${a / b}") // rounds towards zero
println("$a % $b = ${a % b}") // if non-zero, matches sign of first operand
}
else {
println("$a / $b = undefined")
println("$a % $b = undefined")
}
val d = Math.pow(a.toDouble(), b.toDouble())
print("$a ^ $b = ")
if (d % 1.0 == 0.0) {
if (d >= Long.MIN_VALUE.toDouble() && d <= Long.MAX_VALUE.toDouble())
println("${d.toLong()}")
else
println("out of range")
}
else if (!d.isFinite())
println("not finite")
else
println("not integral")
println()
}
}</syntaxhighlight>
}</syntaxhighlight>


{{out}}
{{out}}
<pre>
<pre>
Enter two integers separated by space(s) or q to quit: 2 63
Enter two integers separated by space(s): 2 63
2 + 63 = 65
2 + 63 = 65
2 - 63 = -61
2 - 63 = -61
Line 2,866: Line 2,843:
2 / 63 = 0
2 / 63 = 0
2 % 63 = 2
2 % 63 = 2
2 ^ 63 = 9223372036854775807
2 ^ 63 = 9.223372036854776E18

Enter two integers separated by space(s) or q to quit: -3 50
-3 + 50 = 47
-3 - 50 = -53
-3 * 50 = -150
-3 / 50 = 0
-3 % 50 = -3
-3 ^ 50 = out of range

Enter two integers separated by space(s) or q to quit: q
</pre>
</pre>