Java 模不返回正确值

Java 模不返回正确值,java,modulo,Java,Modulo,我的代码: public static void main (String args[]) throws IOException { while ((sCurrentLine = bufferedReader.readLine()) != null) { if(count == 1){ // Reading via bufferedReader int resultNumber = 0;

我的代码:

    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++;
    }

}
publicstaticvoidmain(字符串args[])引发IOException{
而((sCurrentLine=bufferedReader.readLine())!=null){
如果(计数=1){
//通过bufferedReader读取
int resultNumber=0;
如果(n修饰符==0){
系统输出打印项次(“0”);
}else if(n修饰符==1){
系统输出打印项次(“01”);
}否则{
int a=Integer.valueOf(nextLineString[0]);
int b=整数.valueOf(nextLineString[1]);
int c=整数.valueOf(nextLineString[2]);
对于(int i=kPreviousNumber;i
测试用例表明
第10个修改后的斐波那契数将为845114970
。但不管我做什么,我最终得到了923527,我试图以三个为一组进行乘法,这个概念和斐波那契数列一样,但不是加法,而是用三个数的集合进行乘法。应用模运算时,我是否遗漏了什么?

您使用的:
(a*b*c)
=
((a%mod)*(b%mod)*(c%mod))%mod

如果
(a%mod)
(b%mod)
(c%mod)
是大数,例如
(mod-1)
,则会出现溢出,并且无法得到正确的结果。要避免溢出,您需要执行以下操作:

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

更改此项:

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


整数溢出?为了避免这种情况,我也尝试过这个
int nextNumber=Math.abs((Math.abs(a%1000000007)*Math.abs(b%1000000007)*Math.abs(c%1000000007))%1000000007)
但它仍然返回:273406272,第10个修改后的斐波那契数。预期值:第10个修改后的斐波那契数:845114970您错过了一个模。使用
(a%mod)*(b%mod)
是否仍然存在问题?你已经在回答另一个问题时解决了这个问题。。或者这不适用于这里?怎么会有问题?((a%mod)*(b%mod))%mod(100000007*100000007)<2^63如果(mod-1)*(mod-1)大于2^63,则需要通过求和实现模乘
Math.floorMod(Math.floorMod(Math.floorMod(a , 1000000007) * Math.floorMod(b , 1000000007), 1000000007) * Math.floorMod(c, 1000000007), 1000000007);