Is there a way to implement the log function witch works for string numbers without converting the string to a int? example of string number: char *stringNumber = "432" the string represents only integers(whole Numbers) but they can be near infinitely long the log should return an int as well(represented as a string) if i result is a float the decimal part should be removed (no rounding)
i know that for numbers you can implement:
int logn(int n, int x)
//n is the number , x is the base
{
if (n <= r-1)return 0;
return (1 logn(n/x, x);
}
but for a string i have no idea how to do it
CodePudding user response:
You need to convert the string to a number
char * numStr = "2.7";
double num = strtod(numStr, NULL);
CodePudding user response:
thanks to @EricPostpischil for the answer perform long division, dividing the input number by the base and discarding the remainder. Doing this repeatedly and counting the repetitions produces the logarithm (the number of repetitions until the quotient is less than one is the greatest integer not greater than the logarithm; the answer of @pmg is also a good way to do it i thinks
CodePudding user response:
Even your example function has typos in it. It appears you meant for it to return the integer part of the logarithm base x of n, with a floor function applied to the result. To accomplish this it would have to be:
int logn(int n, int x) // n is the number, x is the base
{
if (n <= x - 1) return 0; // note: x, not r
return (1 logn(n / x, x); // note: x, not 2 for the division
}
All that being said, I don't see any way of taking an arbitrary-base logarithm of a stringified number without converting it to a numeric value first. If you wanted only a base-10 logarithm, it would be possible.