Nagendra Kumar Singh
Nagendra Kumar Singh

Reputation: 197

modulo not returning correct value

My piece of code :

    public static void main (String args[]) throws IOException {
    while ((sCurrentLine = bufferedReader.readLine()) != null) {
        if(count == 1){
            // Reading via bufferedReader


            int resultNumber = 0;
            if (nthModifier == 0) {
                System.out.println("0");
            } else if (nthModifier == 1) {
                System.out.println("0 1");
            } else {
                int a = Integer.valueOf(nextLineString[0]);
                int b = Integer.valueOf(nextLineString[1]);
                int c = Integer.valueOf(nextLineString[2]);
                for (int i = kPreviousNumbers; i < nthModifier; i++) {
                    int nextNumber = Math.floorMod(Math.floorMod(a , 1000000007) * Math.floorMod(b , 1000000007) * Math.floorMod(c, 1000000007), 1000000007);
                    resultNumber = nextNumber;
                    a = b;
                    b = c;
                    c = nextNumber;
                }
            }

            System.out.print(resultNumber + " ");

        }
        count++;
    }

}

The test case says that the 10th modified Fibonacci number will be 845114970. But what ever I do I end up getting 923527, I am trying to multiply in batches of three, the concept is same like fibonacci series, but instead of adding, I am multiplying with set of three numbers. Is there something I am missing while applying the modulo?

Upvotes: 1

Views: 181

Answers (1)

Golam Mazid Sajib
Golam Mazid Sajib

Reputation: 9457

You used : (a * b * c) = ( (a % mod) * (b % mod) * (c % mod) ) % mod..

If (a % mod) & (b % mod) & (c % mod) be large number ex. (mod-1) then there will be overflow and you don't get correct result. To avoid this overflow u need to do this:

( a * b * c ) % mod = ( ( (a % mod) * (b % mod) ) % mod ) * (c % mod) ) % mod

Change this:

Math.floorMod(Math.floorMod(a , 1000000007) * Math.floorMod(b , 1000000007) * Math.floorMod(c, 1000000007), 1000000007);

To

Math.floorMod(Math.floorMod(Math.floorMod(a , 1000000007) * Math.floorMod(b , 1000000007), 1000000007) * Math.floorMod(c, 1000000007), 1000000007);

Upvotes: 1

Related Questions