Reputation: 3930
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
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
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
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