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.
0 件のコメント
採用された回答
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 件)
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
参考
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!