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

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Exponentiation operator step by step in the Fortran 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 Fortran programming language

Source code in the fortran programming language

MODULE Exp_Mod
IMPLICIT NONE

INTERFACE OPERATOR (.pow.)    ! Using ** instead would overload the standard exponentiation operator
  MODULE PROCEDURE Intexp, Realexp
END INTERFACE

CONTAINS

  FUNCTION Intexp (base, exponent)
    INTEGER :: Intexp
    INTEGER, INTENT(IN) :: base, exponent
    INTEGER :: i

    IF (exponent < 0) THEN
       IF (base == 1) THEN
          Intexp = 1
       ELSE
          Intexp = 0
       END IF
       RETURN
    END IF
    Intexp = 1
    DO i = 1, exponent
      Intexp = Intexp * base
    END DO
  END FUNCTION IntExp

  FUNCTION Realexp (base, exponent)
    REAL :: Realexp
    REAL, INTENT(IN) :: base
    INTEGER, INTENT(IN) :: exponent
    INTEGER :: i
  
    Realexp = 1.0
    IF (exponent < 0) THEN
       DO i = exponent, -1
          Realexp = Realexp / base
       END DO
    ELSE  
       DO i = 1, exponent
          Realexp = Realexp * base
       END DO
    END IF
  END FUNCTION RealExp
END MODULE Exp_Mod

PROGRAM EXAMPLE
USE Exp_Mod
  WRITE(*,*) 2.pow.30, 2.0.pow.30
END PROGRAM EXAMPLE


  

You may also check:How to resolve the algorithm Additive primes step by step in the RPL programming language
You may also check:How to resolve the algorithm Constrained random points on a circle step by step in the Run BASIC programming language
You may also check:How to resolve the algorithm Happy numbers step by step in the PARI/GP programming language
You may also check:How to resolve the algorithm Quickselect algorithm step by step in the Delphi programming language
You may also check:How to resolve the algorithm Power set step by step in the XPL0 programming language