Number of Digits of Factorial

Problem

Given an integer $N$, find number of digits in $N!$.

For example, for $N=3$, number of digits in $N! = 3! = 3 \times 2 \times 1 = 6$ is $1$. For $N=5$, number of digits in $5! = 120$ is $3$.

Brute Force Solution

The first solution that pops into mind is to calculate $N!$ and count how many digits it has. A possible solution will look like the following:

int factorialDigit ( int n ) {
    long long fact = 1;
    for ( int i = 2; i <= n; i++ ) {
        fact *= i;
    }

    int res = 0; // Number of digit of n!
    while ( fact ) { //  Loop until fact becomes 0
        res++;
        fact /= 10; // Remove last digit
    }

    return res;
}

This code works, but only for $N \leq 20$. Once $N$ crosses $20$, it no longer fits in a "long long" variable.

Since the factorial of $N > 20$ overflows long long, how about we use "Big Integer" to store the value?

Brute Force Solution with Big Integer

If you don't know what Big Integer is, then know that it is a class for arbitrary large integer. C++ does not support this class so we will have to manually implement it if we want to use C++ to solve problems involving large integers. Or you could use a programming language that supports this class, such as Java.

I will write a post on Big Integer someday, but for now you could just use the Big Int class written by +Anudeep Nekkanti from here.

Multiplication of a Big Integer and an integer takes $O(\text{number of digits of Big Integer})$. Assuming that when calculating $N!$, the number of digits of $N!$ increases by $1$ at each step, it will take $O(N^2)$ time to compute $N!$. But obviously $N!$ does not increase by $1$ digit at each step ( for e.g, multiply by $100$ increases it by $2$ digits ), so worst time complexity is worse than $O(N^2)$.

Solution Using Logarithm

Logarithm of a number is connected to its number of digits, which might not be apparent. What is logarithm? Logarithm of a number $x$, in base $b$, is a real number $y$ such that $x = b^y$. For example:

$$log_{10}1234 = 3.0913151597 \text{ and } 10^{3.0913151597} = 1234$$

In logarithms, the base of the number is important. Since we want the number of digits of $N!$ in decimal, we will work with base $10$.

Number of Digit of an Integer

First, we will apply the logarithm idea on an integer. So where is the connection of logarithm with digit number? Look at the following logarithm values:

$log_{10}(x) = y$
$log_{10}(1) = 0$
$log_{10}(10) = 1$
$log_{10}(100 )= 2$
$log_{10}(1000) = 3$
$log_{10}(10000) = 4$

As the value of $x$ increases, the value of $y$ also increases. Every time we multiple $x$ by $10$, value of $y$ increases by $1$. That is every time number of digit increases, the value of $y$ increases. From this table, we can infer a few things about the log of other values.

If $log_{10}(100)$ is 2, and $log_{10}(1000)$ is 3, then for all value of $x$ where $100 < x < 1000$ , value of $y$ will lie between $2 < y < 3$. Let us try this out.

$log_{10}(100) = 2$
$log_{10}(150) = 2.17609125906$
$log_{10}(500) = 2.69897000434$
$log_{10}(999) = 2.99956548823$

Now note that, for every $100 \leq x < 1000$, value of $y$ is $2 \leq y < 3$. Can you see some relation between value of $y$ and number of digits of $x$?

Yes. If the value of $y$ is of the form $2.XXX$, then $x$ has $2+1=3$ digits.

$$\therefore \text{number of digits of}: x = \lfloor log_{10} (x) \rfloor + 1$$

Also note that, even though theoretically we just need to add 1 to $log_{10}(x)$ before flooring, it is good practice to add eps (where eps is a small value: $eps = 10^{-9})$ while we are at it. Why? Due to precision error, sometimes our program may say that $log_{10}(100) = 1.9999999$ instead of $2$. In order to avoid such scenes, we add eps to it before flooring.

int numberDigit ( int n ) {
    int wrongAnswer = log10(n) + 1; // This may give wrong answer sometimes.
    int rightAnswer = log10(n) + 1 + eps; // This is right.
    return rightAnswer;
}

If you are wondering, where is the floor function, know that in line $3$, we are assigning $log10(n) + 1 + eps$ to an integer. This has same action as $floor()$ function. Also note that we used $log10()$ function instead of $log()$ function. Unlike our calculators, in C++ $log()$ has base $2$.

Extending To Factorial

So how do we extend this idea to $N!$?

Let $x = log_{10}(N!)$. Then our answer will be $res = \lfloor x \rfloor + 1$. So all we need to do is find value of $x$.

$x = log_{10}(N!)$
$x = log_{10}(1 \times 2 \times 3 \times ... \times N)$
$\therefore x = log_{10}(1) + log_{10}(2) + log_{10}(3) + ... + log_{10}(N)$ This is using the law $log_{10}(ab) = log_{10}(a)+log_{10}(b)$

So in order to calculate $x = log_{10}(N!)$, we don't have to calculate value of $N!$. We can simply add log value of all numbers from $1$ to $N$. This can be achieved in $O(N)$.

int factorialDigit ( int n ) {
    double x = 0;
    for ( int i = 1; i <= n; i++ ) {
        x += log10 ( i );
    }
    int res = x + 1 + eps;
    return res;
}

Digits of $N!$ in Different Base

Now what if we want to find how many digits $N!$ has if we convert $N!$ to some other base.

For example, how many digits $3!$ has in the binary number system with base $2$? We know that $(6)_{10} = (110)_2$. So $3!$ has $3$ digits in base $2$ number system.

Can we use logarithms to solve this problem too? Yes.

$$\text{number of digits of x in base B} = \lfloor log_B(x) \rfloor + 1$$

All we need to do is change the base of our $log$ and it will find the number of digits in that base.

But, how do we change base in our code? We can only use log with base $2$ and $10$ in C++. Fear not, we can use the following law to change base of logartihm from $B$ to $C$.
$$log_B(x) = \frac{log_C(x)}{log_C(B)}$$
So in C++, we will use $C = 2$ or $C=10$ to find value of $log_B(x)$.

int factorialDigitExtended ( int n, int base ) {
    double x = 0;
    for ( int i = 1; i <= n; i++ ) {
        x += log10 ( i ) / log10(base); // Base Conversion
    }
    int res = x + 1 + eps;
    return res;
}

UVa 10407 – Simple division

Problem

Problem Link – UVa 10407 – Simple division

Given an array of numbers, find the largest number $d$ such that, when elements of the array are divided by $d$, they leave the same remainder

Solution

We will be using our knowledge about Congruence Relation and GCD to solve this problem. But first, we need to make sure that we understand the problem properly.

Wrong Approach

At first, one might think that $d$ is the $gcd$ of array elements. Surely, dividing elements of the array with $d$ will leave same remainder $0$, but that doesn’t necessarily mean it is the largest possible answer.

For example, suppose the array is $A = {2,8,14,26}$. Then what will be the $gcd$ of array A? $gcd(2,8,14,26) = 2$. Dividing elements of $A$ with $2$ leaves us $0$. So is this our answer? No.

For array $A$, there exists a number greater than $2$ that leaves the same remainder. And that number is $3$. When we divide each element with $3$, it leaves us $2$ as the remainder.

The problem did not ask us to find the number that will leave $0$ as remainder. It asked us to find the largest number $d$ that leaves the same remainder. So for array $A$ the $gcd(A)$ is not the answer. Is $3$ our answer? No. The answer is given below in Example.

Using Congruence Relation

Let us rephrase the problem using congruence relation. Suppose there is an array with elements, $A={a,b,c}$. We need to find the largest number $d$ that leaves the same remainder for each of its element.

Let us consider only ${a,b}$ for now. We need to find $d$ such that it leaves the same remainder when it divides $a$ and $b$. Meaning

$$a \ \equiv \ b \ \text{(mod d)} \ a – b \ \equiv \ 0 \ \text{(mod d)}$$

What does this mean? It means, if $d$ leaves the same remainder when it divides $a$ and $b$, then it will leave no remainder when dividing $a-b$.

Using same logic, we can say that $b – c \ \equiv \ 0 \ \text{(mod d)}$. Therefore, if we find a number that divides $a-b$ and $b-c$, then that number will leave the same remainder when dividing ${a,b,c}$.

This idea can be extended for any number of elements in the array. So $d$ is such a number that leaves no remainder when it divides the difference of adjacent elements in the array.

But wait, there are multiple numbers that can divide the difference of adjacent elements. Which one should we take? Since we want the largest value of $d$, we will take the largest divisor that can divide all the difference of adjacent numbers. There is only one divisor that can divide all the adjacent differences, and that is $gcd( (a-b), (b-c) )$.

Therefore, if we have an array $A={a_1,a_2,a_3…a_n}$, then $d = gcd( a_2 – a_1, a_3- a_2,…a_n – a_{n_1})$.

Careful about negative value of $gcd()$. Make sure you take the absolute value of $gcd()$.

Example

Let us get back to the example we were looking into before. Finding $d$ for the array $A = {2,8,14,26}$. We know that $d$ will divide the difference of adjacent elements completely. So let us make another array that will contain the difference of adjacent elements., $B = {8-2, 14-8, 26-14} = {6,6,12}$. Therefore, $d = gcd ( 6,6,12 ) = 6$.

Summary

  • Let the array of elements be $A = {a,b,c,d…}$.
  • $res \neq gcd(a,b,c,d…)$.
  • $res = gcd ( a-b,b-c,c-d,…)$.

Code

#include <bits/stdc++.h>
using namespace std;

typedef long long vlong;

vlong gcd ( vlong a, vlong b ) {
    while ( b ) {
        a = a % b;
        swap ( a, b );
    }
    return a;
}

vlong arr[1010];

int main () {

    while ( scanf ( "%d", &arr[0] ) != EOF ) {
        if ( arr[0] == 0 ) break; // End of test case

        // A new test case has started
        int cur = 1;

        // Take input
        while ( 1 ) {
            scanf ( "%lld", &arr[cur] );
            if ( arr[cur] == 0 ) break;
            else cur++;
        }

        vlong g = 0; // Start with 0 since gcd(0,x) = x.
        for ( int i = 1; i < cur; i++ ) {
            int dif = arr[i] - arr[i-1]; // Calculate difference
            g = gcd ( g, dif ); // Find gcd() of differences
        }

        if ( g < 0 ) g *= -1; // In case gcd() comes out negative
        printf ( "%lld\n", g );
    }

    return 0;
}

UVa 11388 – GCD LCM

Problem

Problem Link – UVa 11388 – GCD LCM

Given two positive integers $(G, L)$, we have to find a pair of integers $(a,b)$ such that $gcd(a, b)=G$ and $\text{lcm}(a, b)=L$. If there are multiple such pairs, we have to find the pair where $a$ is minimum. Also, both $a$ and $b$ needs to be positive.

Solution

We don’t know the value of $(a,b)$ yet. Here is how I approached the problem.

Value of $a$

What we know that $gcd(a,b) = G$. So, $G$ divides $a$ and $b$. Therefore, $a$ is a multiple of $G$. We also need to make sure that $a$ is as small as possible. So, what is the smallest positive number that can be divided by $G$? The answer is $G$ itself.
$$\therefore a = G$$

Existence of Solution

Next, we know that $lcm(a,b)$ is the smallest positive number which is divisible by both $a$ and $b$. Since $a=G$ and $a \ | \ lcm(a,b)$, it follows that $a = G$ should divide $lcm(a,b) = L$. If $L$ is not divisible by $G$, then no solution exists.

$$\therefore \text{if } (G \not | L), \text{no solution exists}$$

Value of $b$

The value of $b$ can be derived in the following way. We know that:

$gcd(a,b) \times lcm(a,b) = a \times b$
$G \times L = G \times b$
$b = \frac{G \times L}{G}$
$\therefore b = L$.

Summary

  1. $a = G$
  2. If $G \not | L$, no solution exists
  3. $b = L$
  4. $\therefore (a,b) = (G,L)$

Code

Here is the code in C++

#include <bits/stdc++.h>

int main () {
    int kase;
    scanf ( "%d", &kase ); // Input number of case

    while ( kase-- ) {
        int G, L;
        scanf ( "%d %d", &G, &L ); // Take input

        int a, b; // Need to find their value

        a = G;

        if ( L % G != 0 ) {
            printf ( "-1\n" ); // No Solution
            continue;
        }

        b = L;

        printf ( "%d %d\n", a, b );
    }

    return 0;
}