Are you faster than a computer?

What is the output of this C program?

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>

int A[4000], B[4000];
int i,j,k,l,m;

int main(void) {
  for (i=0;i<4000;i++) { A[i]=B[i]=0; } k=-1; m=0;
  while (!A[1000]) {
    A[0]++; B[0]++;
    for (j=0;j<3999;j++) { B[j+1]+=B[j]/13; B[j]%=13; }
    for (j=0,l=-1;j<3999;j++) { 
      if ((A[j]>0) && (k<j)) { k=l=j; }
      A[j+1]+=A[j]/(j+2); A[j]%=(j+2); 
    }
    if (l>-1) m+=B[0];
  }
  printf("%d\n",m);
  return 0;
}

Details and Assumptions

  • The program are designed for a hypothetical computer that allows arbitrarily large numbers (and may result in arithmetic overflow when run with a normal C compiler).

Source : Internet Problem Solving Contest


The answer is 74.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

1 solution

Arjen Vreugdenhil
Jul 14, 2016

Calculation

This code calculates n = 1 M n ! mod 13 \sum_{n=1}^M n!\ \text{mod}\ 13 where M M is the highest integer for which M ! < 1 3 1000 M! < 13^{1000} .

Because n ! mod 13 = 0 n!\ \text{mod}\ 13 = 0 for n 13 n \geq 13 and 13 ! < 1 3 1000 13! < 13^{1000} , this is equal to n = 1 12 n ! mod 13 = 1 + 2 + 6 + 11 + 3 + 5 + 9 + 7 + 11 + 6 + 1 + 12 = 74 . \sum_{n=1}^{12} n!\ \text{mod}\ 13 = 1 + 2 + 6 + 11 + 3 + 5 + 9 + 7 + 11 + 6 + 1 + 12 = \boxed{74}.

Brief explanation

Let N N be the number of times the main loop has been run. Then A [ ] A[] is the representation of N N in base 13, and B [ ] B[] is the factorial representation of N N . That is, N = k = 0 3999 A [ k ] 1 3 k with 0 A [ k ] < 13 ; N = k = 0 3999 B [ k ] ( k + 1 ) ! with 0 B [ k ] k + 1. N = \sum_{k = 0}^{3999} A[k]\ 13^k\ \ \ \ \text{with}\ \ \ 0 \leq A[k] < 13; \\ N = \sum_{k = 0}^{3999} B[k]\ (k+1)!\ \ \ \ \text{with}\ \ \ 0 \leq B[k] \leq k+1.

The condition > 1 \ell > -1 will be true precisely if in representation B [ ] B[] a digit becomes non-zero that has not been non-zero before. This happens precisely with N = 1 ! , 2 ! , 3 ! , N = 1!, 2!, 3!, \dots . (The variable k k keeps track of the last digit that turned non-zero.)

Whenever > 1 \ell > -1 , the least significant digit in the base-13 representation A [ ] A[] is added to the running total m m .

The conclusion is, therefore, that we add N N mod 13 for N = 1 ! , 2 ! , 3 ! , N = 1!, 2!, 3!, \dots The conclusion above follows easily.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...