I also used this picturesque graph to illustrate it |

**Note:**n can be any odd integer, not just a product of two distinct primes.

In general, the "Lonely Squares" algorithm can be summed up in two simple functions that do not require exponentiation to generate [2

^{1}, 2

^{2}, 2

^{3},..., 2

^{k}] where k is the smallest integer such that 2

^{k}= 1 mod n, or in other words k is the order of 2 mod n and n is any odd integer.

- Given an odd integer n list all even integers smaller than n,

followed by all odd integers smaller than n.

- a. Look up the value at initial index.

b. Make that value the initial index.

c. Save and Repeat a and b until the value equals 1.

I first showed a version of this algorithm here but I presented it as a finder of the order of 2 mod n. However, as it can be seen here, it is very easy to modify it to list all powers of 2 mod n up to k where k is the order of 2 mod n.

Below is a Javascript implementation although a lower level language might be more appropriate:

```
/* -------------------------------------------------
This content is released under the GNU License
http://www.gnu.org/copyleft/gpl.html
Author: Marina Ibrishimova
Version: 1.0
Purpose: Find all powers of 2 mod n,
generate the unique portion of row at 2
of the exponentiation table of Z sub n
---------------------------------------------------- */
function powers_of_two_mod(n)
{
var index = 0;
var perm_slot = 2;
var count = 1;
var perm = new Array(); var powers = new Array();
perm = generate_permutation(n);
while(perm_slot != 1)
{
index = perm_slot;
perm_slot = perm[index];
powers.push(perm_slot);
}
return powers;
}
/* -----------------------------------------------
list all even integers smaller than n,
followed by all odd integers smaller than n:
this is 2nd row of the multiplication table of Z sub n
-------------------------------------------------- */
function generate_permutation(n)
{
var index = 0;
var permutation = new Array();
permutation.push(0);
while(index<n)
{
index = index + 2;
if (index == n-1) {
permutation.push(index);
index = 1;
}
permutation.push(index);
}
return permutation;
}
```

__Here'__s a point and click implementation of the algorithm above.