请解释模指数的这段代码

问题描述

这里 x 可以是负数 我无法理解为什么我们在 if(x

public class Solution {
        public int pow(int x,int n,int d) {
    
        long ans;
        if(x==0) return 0;
        if(n==0) return 1;
        if(x<0)  return pow(d+x,n,d);
        
        long temp = pow(x,n/2,d);
        if(n%2==0)
            ans = ((temp%d)*(temp%d))%d;
        else
            ans = ((((x%d)*(temp%d))%d)*(temp%d))%d;
        
        return (int)ans%d;
    
        }
    }

解决方法

从模幂的定义,

c = xn % d 其中 0 <= c < d

当 x 因此通过将 x 更改为 x+d,

if(x<0)  return pow(d+x,n,d);

我们尽量避免否定答案作为解决方案。

最后你不需要再次执行取模,

(int)ans;

但是,您可以通过将最后一行更改为,

来完全忽略 x return (int)(ans+d)%d

代码,

public class Solution {
    public int pow(int x,int n,int d) {
    
        long ans;
        if(x==0) return 0;
        if(n==0) return 1;
        
        long temp = pow(x,n/2,d);
        if(n%2==0)
            ans = ((temp%d)*(temp%d))%d;
        else
            ans = ((((x%d)*(temp%d))%d)*(temp%d))%d;
        
        return (int)(ans+d)%d;
    
        }
    }