Registered User Registered User - 3 months ago 10
C++ Question

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?

Answer

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;