Pregunta

I need to solve this equation in my Java app:

(1080 * j + 1) modulo 7 = 0

Is there some more safe way how to get this value instead of this code? I am not much happy with while loop condition.

    int j = 1;
    int e = 7;
    boolean found = false;
    double r = 0;

    while (!found) {
        r = (1080 * j + 1);
        found = r % e == 0;
        j++;
    }

    int t = (int) (r / e);
¿Fue útil?

Solución

You can improve your solution significantly using maths. You need to find a number that multiplied by 1080 will given a remainder 6 modulo 7 (because after adding 1 it should be divisible by 7). Now 1080 gives remainder 2 modulo 7. Thus you need to find number that multiplied by 2 gives 6 modulo 7. Lets check all 7 possible remainders:

0 * 2 = 0 (modulo 7)
1 * 2 = 2 (modulo 7)
2 * 2 = 4 (modulo 7)
3 * 2 = 6 (modulo 7)
4 * 2 = 1 (modulo 7)
5 * 2 = 3 (modulo 7)
6 * 2 = 5 (modulo 7)

So the only solutions to your problem are the numbers giving remainder 3 (modulo 7) and all such numbers are solutions of the equation.

Otros consejos

(1080*j + 1)% 7 =((1080*j)%7 + 1%7 )%7

And (1080*j)%7 = ((1080%7)*(j%7))%7 = (2*(j%7))% 7

And actually, j only need to run from 0 to 6, as you can clearly see that this is a periodic cycle, which help you to avoid infinite loop, as well as any number (not necessary 7)

(1080*j+1) mod 7 = 0 => 1080*j = 1 (mod 7). So you can use For loop from 0 to 6 like this :

int j;
for(int i=0; i<7; i++){
    if((1080*i) % 7==1) {
         j=i; break;
    }
}

Here is a way to simplify the equation :-

(1080*j + 1)mod 7 = 0

(1080*j)mod7 = 6

by multiplication theorem of modular arithmetic : -

(a*b)%k = (a%k * b%k)%k hence (1080*j)%7 = (1080%7 * j%7)

1080%7 = 2

hence (1080*j)%7 = (2* j%7)%7 = 6

Now j%7 could have values (0,1,2,3,4,5,6)

now of all possible values j%7 = 3 would give (2*3)%7 = 6

j%7 = 3

therefore j = k*7 + 3 is solution to equation where k is any whole number

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top