How to resolve the algorithm Exponentiation operator step by step in the Nim programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Exponentiation operator step by step in the Nim programming language

Table of Contents

Problem Statement

Most programming languages have a built-in implementation of exponentiation.

Re-implement integer exponentiation for both   intint   and   floatint   as both a procedure,   and an operator (if your language supports operator definition). If the language supports operator (or procedure) overloading, then an overloaded form should be provided for both   intint   and   floatint   variants.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Exponentiation operator step by step in the Nim programming language

Source code in the nim programming language

proc `^`[T: float|int](base: T; exp: int): T =
  var (base, exp) = (base, exp)
  result = 1

  if exp < 0:
    when T is int:
      if base * base != 1: return 0
      elif (exp and 1) == 0: return 1
      else: return base
    else:
      base = 1.0 / base
      exp = -exp

  while exp != 0:
    if (exp and 1) != 0:
      result *= base
    exp = exp shr 1
    base *= base

echo "2^6 = ", 2^6
echo "2^-6 = ", 2 ^ -6
echo "2.71^6 = ", 2.71^6
echo "2.71^-6 = ", 2.71 ^ -6


  

You may also check:How to resolve the algorithm Vector step by step in the Nim programming language
You may also check:How to resolve the algorithm Fibonacci sequence step by step in the Potion programming language
You may also check:How to resolve the algorithm RIPEMD-160 step by step in the C programming language
You may also check:How to resolve the algorithm Execute Computer/Zero step by step in the Go programming language
You may also check:How to resolve the algorithm Cuban primes step by step in the Groovy programming language