-1

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..

luckyging3r
  • 3,047
  • 3
  • 18
  • 37

3 Answers3

4

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;
Tyson Graham
  • 227
  • 3
  • 9
3

The implementation of a logarithm is most times a tayler function with approximates logarithm to the base e. To get the logarithm to any other base you do something like this:

#include <cmath>
double y = std::log(x)/std::log(base);

Description:

  • std::log() natural logarithm to base e.
  • y = result
  • base = base of the logarithm. Like 2 or 10.

For your reference:

schorsch_76
  • 794
  • 5
  • 19
1

Here's a better implementation without using the math.h library. I might have some superfluous code as it's been like a year since I have written in C++. (Shame on me) Thanks for your question it got me wanting to brush up on my C++!

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
  float base = 0;
  float answer = 0;
  int exponent = 0;
  cout.precision(4);

  cout << "Please type in your base \n";
  cin >> base;
  cout << "Please type in your answer\n";
  cin >> answer;

  cout << fixed;

  while (answer > base)
   {
     answer /= base;
     exponent++;
   }

  cout << "The exponent is: " << exponent << endl;
  cout << "The Remainder is: " << fixed << answer << endl;
  return 0;
}
Tyson Graham
  • 227
  • 3
  • 9