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

1 次查看(过去 30 天)
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.

采纳的回答

Guillaume
Guillaume 2015-8-28
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 个评论
Tony
Tony 2015-8-29
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

请先登录,再进行评论。

更多回答(1 个)

Walter Roberson
Walter Roberson 2015-8-28
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 个评论
Tony
Tony 2015-8-29
编辑:Tony 2015-8-29
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.

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 MATLAB 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by