A Bogus
A Bogus

Reputation: 3930

C# method for solving missing exponent

With the equation X^Y = Z, how can I write a c# method, to solve for Y? Does one already exist?

Here are some examples of the data I will have -

2^Y = 8

3^Y = 9

Upvotes: 0

Views: 350

Answers (4)

Jacques
Jacques

Reputation: 13

You can find out how many time Z can be devided by X.

Hope this helps.

while (Z > X) 
{
  Z = Z / X;
  Y++;
}

Upvotes: 0

Mio Bambino
Mio Bambino

Reputation: 544

You're looking for Math.Log.

With that you can do:

x = Math.Log(8) / Math.Log(2)

Also not that there is a Math.Log10 which is the logarithm by base 10 - the outcome is yet the same.

Upvotes: 1

h__
h__

Reputation: 793

Try this

Y=Math.Log(8) / Math.Log(2)

Upvotes: 4

Omid CompSCI
Omid CompSCI

Reputation: 1902

Not the most optimized option but you can iterate through a for-loop of huge amount of numbers, and check one by one iteratively. Just a solution that popped up in my head. Code would look something like:

    int base = 2;
    int exponent;
    int result = 8;

for(int i = -9999; i<= 10000000; i++)
{
  exponent = i;
  if(Math.Pow(2,exponent) == result)
{
 WriteLine($"Y = {exponent}");
}

Upvotes: 0

Related Questions