C program or source code that calculates and returns logarithm . For example, if n = 64, then your function should return 6, and if n = 129, then your function should return 7. Let us see how to use C program to find logarithm of number.
Following is a solution using recursion for C program to find logarithm of number.
#include<stdio.h> unsigned int Log2n(unsigned int n) { return (n > 1)? 1 + Log2n(n/2): 0; } int main() { unsigned int n = 32; printf("%u", Log2n(n)); getchar(); return 0; }
Let us try an extended version of the problem.
Writing a one line function Logn(n ,r) which returns . Following is the solution for the extended problem to C program to find logarithm of a number with any base.
#include<stdio.h> unsigned int Logn(unsigned int n, unsigned int r) { return (n > r-1)? 1 + Logn(n/r, r): 0; } int main() { unsigned int n = 256; unsigned int r = 4; printf("%u", Logn(n, r)); getchar(); return 0; }
Let us know if you face any issues in compiling the codes. Write in form of comments.
Regards for helping out, good information. “I have witnessed the softening of the hardest of hearts by a simple smile.” by Goldie Hawn.
I savour, result in I found just what I was having a look for. You’ve ended my 4 day long hunt! God Bless you man. Have a great day. Bye
chanel bags http://chanelbagssale.overblog.com/
This code will give you just the interger value. It will not return the decimal part.
I wondered about the ability to return a float value as well
Is there a way to return the full logarithmic decimal value using a recursion of this fashion?
Why the log value is not calculated and stored in float. I think it should be float because using int always degrades a value to integer from float rounding the value to nearest integer (that can be in some cases wrong).
My point is that data type to store n and r can be int but result that is log n to base r must be stored in a float, so that we can get some values after decimal. Log calculations are meant to be precise and thats why we use values after decimal too. Using above code we will always get same value for a particular range.
ie. Considerng base 10, Log 10 = 1 and Log 100 = 2 and for any n in range [10, 99] , your code will always output 1, That’s quite right, but not absolutely right that can be achieved If we use float.