log

Compute natural logarithm of the element
Our output for log n base E is approximately now equal to (c-1). 

Example:

Input:  n=5.5
Output: log(n)= 1.74

Approach

Java

public class CalculateLog {
    // base value
    public static final double E = 2.718281828459045;

    public static void main(String[] args) {
        double n = 5.5;
        double c = log(n);
        System.out.println("log value of n approximately: " + c);
    }

    private static double log(double n) {
        double c = 0;
        while (n > 1) {
            n = n / E;
            c++;
        }
        c = c + n;
        return c - 1;
    }
}

C++

#include<bits/stdc++.h>
using namespace std;

// base value
double E = 2.718281828459045;
double log(double n
{
        double c = 0;
        while (n > 1) {
            n = n / E;
            c++;
        }
        c = c + n;
        return c - 1;
}
int main()
{
   double n = 5.5;
   double c = log(n);
   cout<<"log value of n approximately: " <<c;
    return 0;
}



No comments:

Post a Comment