Mayur Kharche - 4 months ago 18

C Question

I have an array of integer element range up to

`10^5`

Example:

`Array : 2,4,6,7`

multiplication result: 336 and the first element is 3.

Obviously I cannot multiply the elements with the range up to 10^5.

How can I track only the first digit during multiplication?

Answer

In `c`

or `c++`

make integer data type as `long double`

such that first digit of number is before decimal point and rest are after decimal point.

Above can be done as follows:-

```
long double GetFraction(int number){
int length = (int) log(number) + 1; // this will give number of digits in given number. And log is log base 10.
long double fraction = (long double) number / (10^(length - 1);
return fraction;
}
```

Example :-

Let `number = 12345`

```
length = log(12345) + 1 = 5;
fraction = (long double) 12345 / (10^4) = 1.2345
```

Now for all integers in array find fraction as mention above and multiply them as follow:-

```
int GetFirstDigit(int arr[] , int size){
if(size == 0)
return 0;
long double firstDigit = 1.0;
for(int i = 0 ; i < size ; i++){
firstDigit = firstDigit*GetFraction(arr[i]);
if(firstDigit >= 10.00) // You have to shorten your number otherwise it will same as large multiplication and will overflow.
firstDigit/=10;
}
return (int) firstDigit;
}
```

Disclaimer:- This is my approach and I don't have any formal proof about accuracy of result. But I have verified result for integer up to `10^9`

and array size up to `10^5`