필터 지우기
필터 지우기

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 CenterFile Exchange에서 MATLAB에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by