Page 167 - ARM 64 Bit Assembly Language
P. 167
Structured programming 153
16 printf("Enter x: ");
17 goodval = scanf("%d", &x);
18 if(goodval == 1)
19 printf("%d! = %lu\n", x, factorial(x));
20 } while(goodval == 1);
21 return 0;
22 }
Write this program in AArch64 assembly.
5.13. For large x, the factorial function is slow. However, a lookup table can be added to the
function to avoid performing deep recursion x every time. This technique is commonly
known as memoization or tabling, but is sometimes called dynamic programming. The
following C implementation of the factorial function uses memoization. Modify your
AArch64 assembly program from the previous problem to include memoization.
1 #define TABSIZE 50
2
3 /* The factorial function calculates x! */
4 unsigned long factorial(int x)
5 {
6 /* declare table and initialize to all zero */
7 static unsigned long table[TABSIZE] = {0};
8
9 /* handle base case */
10 if(x<2)
11 return 1;
12
13 /* if x! is not in the table and x is small enough,
14 then compute x! and put it in the table */
15 if((x < TABSIZE) && (table[x] == 0))
16 table[x] = x * factorial(x-1);
17
18 /* if x is small enough, then
19 return the value from the table */
20 if(x < TABSIZE)
21 return table[x];
22
23 /* if x is too large to be in the table, use
24 a recursive call */
25 return x * factorial(x-1);
26 }

