Question: I have an app that creates custom files that are shown in a gallery. They are not images or other standard media files. Because the files are large, I ask users for access to a folder in which the files will be stored.

So far so good.

Reading those files or file info via DocumentFile is so much slower than via File. Operations like

```
DocumentsContract.findDocumentPath()
documentFile.isFile()
documentFile.getName()

```

take up to 15ms each, which accumulates to a large time when reading a large number of files.

What's the best way to handle this? Is there another way to do this? I don't want the files to be in internal app memory or users might lose their work when they uninstall the app.

Thanks in advance! This is stressing me out a lot.

Answer: 
Imagine you want to find `test(10)`. As a human, you will naturally find the algorithm to find that. Start making a table of results.

```
n = 0 -- result is 0
n = 1 -- result is 1
n = 2 -- result is 2

```

To continue the table, just use the last few numbers in the table:

```
n = 0 -- result is 0
n = 1 -- result is 1
n = 2 -- result is 2
n = 3 -- result is 3
n = 4 -- result is 6
...

```

The algorithm is "take last 3 numbers and add them, then write the answer in the new line in your table". This is easy to implement. Something like this:

```
n1 = 2
n2 = 1
n3 = 0
for i from 3 to n
    // Imagine you have everything up to i written on paper.
    // Here n1 is the last number, n2 is before that, n3 is before that.
    // Try to continue writing your table.

    result = n1 + n2 + n3

    // Now imagine you have written the result on paper.
    // What are the 3 last numbers now?

    n3 = n2
    n2 = n1
    n1 = result

    // Verify that in a debugger for better visualization.

// Now, after the loop is finished, n1 (the last number) is the correct answer.

return n1

```
Time to get out the tail recursion hammer

```
static int testk(int i, int n, int a, int b, int c)
{
   if (i == n) return a + b + c;
   return testk(i + 1, n, a + b + c, a, b);
}

int test(int n) {
    if (n < 2) return n;
    return testk(3, n, 2, 1, 0);
}

```

This is a direct translation of anatolyg's answer to tail recursion.