Mathematically the number of digits in given integer > 0 can be determined with logarithm.

The number of digits in an integer > 0 is

Trunc(Log_{k}(number)) + 1

Trunc comes from the Pascal programming language and means truncation. ”number” is 10 base system number of *k* base system number.

The idea is to examine how many powers of base system *k* there is in the number, that is how many times the given number can be divided with the base number until we get number < 1. With this our friend logarithm helps us to determine that. As a reminder, logarithm is reverse operation to power.

Examples:

In 10 base system in number 12345678 there is 7 powers of 10: Trunc(Log_{10}12345678) = 7, the number of digits is 7 + 1 = 8.

The hexdecimal system number 999_{16} = 2457_{10}, Log_{16} 2457 = 2.8156…, the number of digits is 2 + 1 = 3.

Hex number FF_{16} = 255_{10}, Log_{16} 255 = 1.9985…, the number of digits is 1 + 1 = 2.

Binary number (*k *= 2) 10000000_{2} = 128, Log_{2} 128 = 7, the number of digits is 7 + 1 = 8.

Binary number 10100001_{2} = 161_{10}, Trunc(Log_{2 }161) = Trunc(7.33091…) = 7, the number of digits is 7 + 1 = 8.

*Image courtesy of Stuart Miles at FreeDigitalPhotos.net*

Via programming the number of digits can be determined by dividing the number by the base system number *k* until the number being divided is < 1. Now the number of digits is the number of divisions.

Below is a C programming language program that determines the number digits of 10 base system number that can be positive or negative decimal number:

#include <stdio.h>
#include <math.h>
int detDigits(double);
void main(void) {
double decimalnumber;
int number_of_digits;
printf("Give a decimal number: ");
scanf("%lf", &decimalnumber);
number_of_digits = detDigits(decimalnumber);
printf("The number of digits is %d.",number_of_digits);
}
int detDigits(double dn) {
int digits_integer_part, digits_decimal_part;
int worknumber;
if (dn == 0) return 1;
if (dn < 0) dn = -dn;
digits_integer_part = ((int)log10(dn)) + 1;
dn = dn – (int)dn;
worknumber = (int) dn;
while (worknumber % 10 != 0) {
dn = dn * 10;
worknumber = (int)dn;
}
/* Variable "worknumber" now holds the number of digits
of decimal part of the given number + 1 */
digits_decimal_part = worknumber – 1;
return digits_integer_part + digits_decimal_part;
}

Another way of determining the number of the digits is of course converting the decimal number to string and by examining the number of characters.

### Like this:

Like Loading...

*Suositellut*

Posted by Markus in Mathematics, Programming Tags: Logarithm, powers