How to break loop if number repeats -Matlab

Viewed 54

I recognized this is a quite hard problem for me. I asked this problem on official Matlab side but no-one could help me either so maybe someone of you can come up with an outstanding approach.

In detail my Problem consist of:

N = 100 %some number
G = 21  %random guess < N

for x = 1:N;
a = mod(G^x,N);
end

Now I want the calculation of a to stop, if a number repeats.

For example: a = 1, 2, 3, 1 -break

Seems simple but I just can't handle it right after many tries.

For instance I've put:

for x = 1:N
    a = mod(G^x,N);
    b = unique(a);
    if a ~= b
        break 
    end 
end

but doesn't seem to work bc. it's not element wise I guess.

1 Answers

This approach keeps a running log of the past Results and uses the ismember() function to check if the current value of a has been previously seen.

Output Results

clc;
N = 100; %some number
G = 21;  %random guess < N

Results = NaN(1,N);
for x = 1:N
a = mod(G^x,N);
disp(a);
if ismember(a,Results)
    disp("-break");
    break
end
Results(x) = a;
end

Ran using MATLAB R2019b

Related