Azzera filtri
Azzera filtri

Possible to mod a number in the middle of a cycle?

1 visualizzazione (ultimi 30 giorni)
Here is a portion of my code I need help with:
for m = 1:k
for j = 1:FEE
number = m.^j;
if number >= 10000000
number = mod(number,k);
else
end
To illustrate my problem, lets look at a specific example.
Lets say m = 9, we want to look at when j = 9, 18
9^9 is okay because you get no round off error, 9^18 on the other hand gives round off error.
Is there a way to run 9^any power and mod it when it exceeds the limit 10000000 at any point?
I feel like in this portion of my code matlab is running 9^18 for example, noticing it exceeds 10000000 then modding (9^18 first, then modding would result in round off error right?), I want matlab to run 9*9...* 9 and mod it every single time it exceeds 1000000 before finishing the multiplication.

Risposta accettata

Guillaume
Guillaume il 28 Ago 2015
You're performing modular exponentiation. There are plenty of fast algorithms around that do not involve ever calculating the exponentiation first (it's an important part of cryptography), including on the wiki page linked or on the file exchange.
  1 Commento
Tony
Tony il 29 Ago 2015
Thanks for sending me that information. To be honest none of those codes made sense nor did I use any of them, but after looking at a few, it gave me an idea that now helps my code run perfectly now. Thanks again for the spark.
K = number you are looking for primitive roots of
FEE = Euler's totient of K
for m = 1:k
kk = 1;
while kk <= FEE
PossiblePrim(1) = m;
PossiblePrim(kk+1) = mod(m*PossiblePrim(kk),k);
kk = kk + 1;
end

Accedi per commentare.

Più risposte (1)

Walter Roberson
Walter Roberson il 28 Ago 2015
for m = 1:k
number = 1;
for j = 1:FEE
number = number * m;
if number >= 10000000
number = mod(number,k);
end
end
fprintf('m = %g, number = %g\n', m, number);
end
  1 Commento
Tony
Tony il 29 Ago 2015
Modificato: Tony il 29 Ago 2015
Hey Walter, the reason I accepted Guillaume's answer is because when I first read your code, it seemed too confusing, but now I see why this would work, but it would take a lot longer (my code might freeze).
You are asking it to run m^k (j has no input on this example) instead of running m^FEE.
Again it wasn't till all of this came to me and I fixed my code that I now see what you were trying to say, thanks again though.

Accedi per commentare.

Categorie

Scopri di più su MATLAB 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!

Translated by