Search code examples
c++radixlogarithmexponent

c++ trying to figure out logarithms calculations


So if I am understanding c++ and logarithms correctly. Something like this should give me the base that I am looking for?

I am having some issues, but think that this way is a correct start.

#include <iostream>
using namespace std;

int main(void)
{
   int x = 2;
   int y = 64;
   int value = log x (y);
   cout << value << endl;

   return 0;    
}

This should display "6", but I am not sure how to really use the logarithm library..


Solution

  • There are three parts of a logarithm problem. The base, the argument (also called power) and the answer. You are trying to find the number of times 2 (the base) must be multiplied to get 64 (the answer).

    So instead of dealing with powers and guessing. Let's just count the number of times we divide the answer 64, by the base, until we get 1.

    64 / 2 = 32 
    32 / 2 = 16
    16 / 2 = 8
    8 / 2 = 4
    4 / 2 = 2
    2 / 2 = 1
    

    Here we count 6 lines, so you divided the answer 64, by the base 2, 6 times. This is the same as saying you raised 2 to the 6th power to get 64.

    Hmm for that to work you would need the math.h library. If you want to do this without it. You could do a loop where you constantly divide by the base given by the user.

    int base = 0;
    int answer = 0;
    int exponent = 0;
    cout << "Please type in your base";
    cin >> base;
    cout << "Please type in your answer";
    cin >> answer;
    while (answer != 1)
        {
            answer /= base;
            exponent++
        }
    cout << "The exponent is " << exponent;