I tried to write a function that duplicated `PowerMod[a, b, n]`

count `a ^ b`

mod `n`

, I am currently testing `3 ^ x mod 353`

and different `x`

, I've found that my results match those of the built-in feature until I strike `x = 10 ^ (308)`

, At this point, I get a recursion error. Is there a reason that Mathematica's built-in functions still work on these values?

```
pmod[a_, b_, mod_] : =
module[{l, z, binarylist = IntegerDigits[b, 2]val = 1}
l = length[binarylist];
clear[z];
z[1] = a;
z[j_] : = z[j] = Mod[z[j - 1]^ 2, mod];
z[l];
Do[
If[binarylist[[Binarylist[[binärliste[[binarylist[[j]]== 1,
val * = z[l - j + 1]; val = mod[val,
mod]],
{j, 1, l}];
val]
```

I use `l - j + 1`

because I want when `j = 1`

if binary list[[[[[j]]= 1; val * = z[j]when `j = 2`

; want `val * = z[j - 1]`

, …, `j = 1, val * = z[1]`

, This is a result of Mathematica, lists start at 1 and not at 0.

```
pmod[3, 10^305, 353]
```

`140`

```
PowerMod[3, 10^305, 353]
```

`140`

```
pmod[3, 10^308, 353]
```

$ RecursionLimit :: reclim2: Recursion depth of 1024 exceeded during the evaluation of mod[z$50178[4-1]^ 2.353],

`185`

```
PowerMod[3, 10^308, 353]
```

`58`

### To edit

I thought that might be because 10 ^ 308 exceeds 2 ^ 1024, but my calculations show that this happens at 10 ^ 309. If I use 2 ^ 1023 (I do not understand why I would do it, but I may think that too much), that explains the mistake.