简体   繁体   中英

How do I keep variable below a constant if the variable value is reused?

I have a code like

for(...)
{
    K=K*X; //X is some equation
    answer=answer+K%C;
}

The variable answer is all I am interested in, while K is only a intermediate value. As you can see, I am interested in only K%C not K . But I cannot do K=K%C in for loop as it will give wrong result. But currently the K value grows very fast and overflows.

How could I control value of K while not getting wrong results either?

You can exploit the identity

ab mod n = (a mod n)(b mod n) mod n

And replace K = K * X; with K = ((K % C) * (X % C)) % C;

Then answer = answer + K % C; becomes answer += K;

Try this:

K = K%C;

for (...)
{
    K = K*X%C;
    answer = answer+K;
}

Could not comment on other answer yet, but I believe the initialization of K = K%C; outside the loop is not correct. Just the loop is all you need.

for( ... )
{
     K=K*X%C;
     answer=answer+K;
}

The reason for why this works is that it's not necessary to accumulate the extra multiples of C within K. Suppose K is first iteration, and K' is the next iteration, then K'*X = (K/C)*X + (K%C)*X. So we can drop the (K/C)*X part in each iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM