# loop: stop if value repeats

18 visualizzazioni (ultimi 30 giorni)
Niklas Kurz il 21 Gen 2021
Risposto: Jan il 24 Gen 2021
In my case this is based on
N = Number
G = Guess
x = 1:N
R= mod(G^x,N)
if R repeats I want the calculation mod(G^x,N) to stop and tell me the steps P that it needed to to get to R again
for example if R = 1, 4 3, 2, 1 -stop, P = 4
##### 2 CommentiMostra 1 commento meno recenteNascondi 1 commento meno recente
Jan il 24 Gen 2021
The question is not clear yet. This makes it hard to find an answer.

Accedi per commentare.

### Risposta accettata

Jan il 24 Gen 2021
N = Number;
G = Guess;
x = 1:N;
R = nan(1, N);
found = N;
for k = 1:N
R(k) = mod(G^x(k), N);
if any(R(1:k-1) == R(k))
found = k;
break
end
end
R = R(1:found)
##### 0 CommentiMostra -1 commenti meno recentiNascondi -1 commenti meno recenti

Accedi per commentare.

### Più risposte (1)

Bob Thompson il 21 Gen 2021
I'm assuming you have all four of these commands within some kind of loop. Without the loop I have not tested what I'm going to suggest adding.
To do what you're asking you need to record all the values of R, this can be done by indexing R. If you aren't running an integer for loop, starting at 1, then you'll need to add a counter for each time you loop.
Then you just need an if check to determine if the loop needs to be broken.
N = Number
G = Guess
x = 1:N
R(count) = mod(G^x,N)
if sum(R==R(count))>1
P = length(R)-1;
break
end
end
##### 3 CommentiMostra 2 commenti meno recentiNascondi 2 commenti meno recenti
Niklas Kurz il 23 Gen 2021
I want the loop to stop if it found a repeated number because I need it to count the period in order that I can continue processing wih it.

Accedi per commentare.

### Categorie

Scopri di più su Loops and Conditional Statements in Help Center e File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!