WBE_Praktikum_1/power.js

47 lines
1.3 KiB
JavaScript
Raw Permalink Normal View History

2022-09-29 12:36:51 +02:00
const { AssertionError } = require('assert')
const assert = require('assert')
const power_for = function (base, exponent) {
let result = 1
for (let count = 0; count < exponent; count++) {
result *= base
}
return result
}
const power_rec = function (base, exponent) {
if(exponent == 0) {
return 1;
}
return base * power_rec(base, exponent - 1)
}
const power_rec_opt = function (base, exponent) {
if(exponent == 0) {
return 1;
}
else if(exponent % 2 == 0) { //gerade
let value = power_rec_opt(base, exponent / 2)
return value * value
} else { //ungerade
return base * power_rec_opt(base, exponent - 1)
}
}
const power = function(base, exponent){
assert.ok(Number.isInteger(base), "Exponent is not an Integer")
assert.ok(Number.isInteger(exponent), "Exponent is not an Integer")
assert.ok(base >= 0)
assert.ok(exponent >= 0)
return power_rec_opt(base, exponent)
}
//console.log("With for Loop: " + power_for(2, 10)) // → 1024
//console.log("With recursion: " + power_rec(2, 10)) // → 1024
//console.log("With recursion optimized: " + power_rec_opt(2, 10)) // → 1024
// console.log(power(2, 10)) // → 1024
// console.log(power(2, 2.5)) // !! AssertionError
module.exports = { power }