exponent function Without POW or Multiplication

Pages: 12
Alb13G, congratulations on your journey into programming! I hope you find it as fun as the members on this forum do.

I think you'll find that most of the tasks on sites like codechef and ProjectEuler will require more math than you have.

Regarding the current problem, here are some details on how you can solve it using logarithms.

Mathematically, the log() function is the inverse of the exponent function. So if y = ex then x = log(y). Here "e" is a constant whose value is about 2.72. We use e because of some cool properties that don't matter for this discussion.

Now the fun part. It turns out that log(a*b) = log(a) + log(b). Using this property, you can multiply numbers a and b like so:
1. Compute X = log(a) + log(b).
Because of the property above, we know that this number is also equal to log(a*b).
2. Compute Y = eX
Since log(x) and ex are inverse function, that means that elog(a*b) = a*b
3. Voila! Y is a*b!

In C++ the functions are declared in header file <cmath>. Function log() does log and function exp() does exponentiation.

If you have a scientific calculator, these will be shown as functions ln(x) and ex.

Here's an example to test your program against. Note that the numbers shown are approximations. Your program might display a value that's close to 20, but not exactly equal to it.

a=2 b=10
log(2) = 0.693147
log(10) = 2.302585
0.693147+2.302585 = 2.995732
e2.995732 = 20

Good luck!
I was saying you can use the * function you wrote, using adds...

as for the above, one more: lg is (base 2).

as for built in math, if you start playing around, note that trig etc are all in radians, not degrees.

in the spirit of the exercise, here is a rough log10 hand-written. Ill see if I can find a cute way to do it without using pow() inside later. I only had a couple min right now.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
double logx(double in)
{
  double result = 0;
  double t = in;
  double hone = 0.5;
  int i;
  while(t > 1)
  {
	t/= 10;  
	result ++;
  }
  for(i = 0; i < 25; i++)
  {  
  t =  pow(10,result);  
  if(t > in)
    result -= hone;
  else
	result += hone;
   hone/= 2;
  }
	return result;
}


I don't have the energy for it. Looks like doing a hand-rolled power to handle decimals is fairly annoying, you have to run the nth root algorithm and split the power into integer/decimal parts etc.
Last edited on
Topic archived. No new replies allowed.
Pages: 12