C++ horners方法求多项式为何没有溢出

C++ horners方法求多项式为何没有溢出,c++,algorithm,hash,polynomials,C++,Algorithm,Hash,Polynomials,求值多项式 基本上,我使用以下公式计算字符串的哈希值 我在计算多项式,我在使用朴素的方法 计算多项式的一种简单方法是逐个计算所有项。首先计算x^n,将该值乘以cn,对其他项重复相同的步骤并返回总和。使用以下算法 struct hashFunction { std::size_t operator() (const std::string& str) const { unsigned int uiHashValue = 0; unsign

求值多项式

基本上,我使用以下公式计算字符串的哈希值

我在计算多项式,我在使用朴素的方法 计算多项式的一种简单方法是逐个计算所有项。首先计算x^n,将该值乘以cn,对其他项重复相同的步骤并返回总和。使用以下算法

struct hashFunction {
    std::size_t operator() (const std::string& str) const {

        unsigned int uiHashValue     = 0;
        unsigned int uiPowerValueIdx = 0;
        std::uint64_t uiSum          = 0;
        for(unsigned int uiIdx = 0; uiIdx < str.length(); uiIdx++, uiPowerValueIdx++) {

            unsigned int uiCharAsciiVal = (str[uiIdx]);
            // calculate power of x ^ uiPowerValue
            std::uint64_t uiXToPowerValue     = 1;
            std::uint64_t uiIntermediateValue = uiXValue;
            unsigned int uiPowerValue        =  uiPowerValueIdx;
            std::cout << uiIdx << " char is " << str[uiIdx] << " ascii value " << uiCharAsciiVal ;
            while(uiPowerValue > 0) {
                // if power value is multiply x value with intermediate value
                if((uiPowerValue & 1) == 1) {
                    uiXToPowerValue = ((uiXToPowerValue % uiLargePrime) * (uiIntermediateValue %uiLargePrime)) %uiLargePrime ;
                }
                uiPowerValue = uiPowerValue >> 1;
                uiIntermediateValue = ((uiIntermediateValue % uiLargePrime) * (uiIntermediateValue % uiLargePrime)) % uiLargePrime;
            }
            std::cout << " power value " << uiXToPowerValue<< std::endl;
            uiSum = uiSum + (((uiCharAsciiVal % uiLargePrime )* (uiXToPowerValue % uiLargePrime)))%uiLargePrime;

        } // for loop

        std::cout << (uiSum % uiMValue) << std::endl;
        return uiSum % uiMValue;
    }
};
struct hashFunction{
std::size\u t运算符()(常量std::string&str)常量{
无符号整数uiHashValue=0;
无符号整数uiPowerValueIdx=0;
标准:uint64_t uiSum=0;
for(unsigned int uiIdx=0;uiIdxstd::cout你两个问题的答案都在这一行:

uiSum = uiSum + (((uiCharAsciiVal % uiLargePrime )* (uiXToPowerValue % uiLargePrime)))%uiLargePrime;
这就是溢出发生的地方。你也需要在这里取模

uiSum = (uiSum + (((uiCharAsciiVal % uiLargePrime )* (uiXToPowerValue % uiLargePrime)))%uiLargePrime) % uiLargePrime;

只要字符串以null结尾,就不会引起问题
uiSum = (uiSum + (((uiCharAsciiVal % uiLargePrime )* (uiXToPowerValue % uiLargePrime)))%uiLargePrime) % uiLargePrime;