What you mistake is that a and p are represented as DOUBLES. Can you compute a number as you want to do? What happens?
Do you see there are precision problems? Double precision arithmetic overflows when you try to compute those large powers. And then mod must fail.
Instead, while you CAN use syms to compute the moduli, it is far better to learn about the powermod function.
Powermod EFFICIENTLY compute the modulus here, without ever computing the number a^x, and so we won't see an overflow, at least not until the modulus gets too large.
table((1:100)',y)
ans =
Var1 y
____ _____
1 3
2 9
3 27
4 81
5 243
6 729
7 2187
8 6561
9 19683
10 4552
11 13656
12 40968
13 13910
14 41730
15 16196
16 48588
However, it sounds as if you want to know how to solve for the primitive roots modulo some prime.
In there, you would read:
"In particular, for a to be a primitive root modulo n, φ(n) has to be the smallest power of a that is congruent to 1 modulo n."
We would also learn that
If a is a primitive root modulo a prime p, then mod(a.^(p-1)/2,p) == p-1.
Remember, for n prime, the Euler Totient function has the property that phi(n)==n-1.
What, for example, are the primitive roots of 11? This will be the set of integers r in the interval [2,n-2], such that
powermod(r,(n-1)/2,n) == -1 == n-1 (mod n)
primitiveroots = rtest(powermod(rtest,(n-1)/2,n) == n-1)
And on that wiki page, we would see the primitive roots of 11 are [2,6,7,8].
Finally, we would see this comment:
No simple general formula to compute primitive roots modulo n is known.
So, at best, for a large prime modulus, the above computation seems about the best you can do.