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

1 回表示 (過去 30 日間)
Tony
Tony 2015 年 8 月 28 日
編集済み: Tony 2015 年 8 月 29 日
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 Center および File ExchangeMathematics についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by