码迷,mamicode.com
首页 > 其他好文 > 详细

mod

时间:2019-12-27 09:24:05      阅读:76      评论:0      收藏:0      [点我收藏+]

标签:mod   @param   大于等于   oca   ret   for   公式   大于   return   

/**
 * 字符数组模拟大整数取余 a % b
 *大整数取模
 *
 *思路:首先,将大整数根据秦九韶公式写成“自左向右”的形式:4351 = ((4 * 10 + 3) * 10 + 5) * 10 + 1,然后利用模的性质,逐步取模。
 * @param: const unsigned char a[]
 * @param: const unsigned char b[]
 * @output: null
 * @return: unsigned char result[]
 * @caution:需保证a%b后,结果位数足够长,可以保存,  同时result长度要大于等于a
 */
function bigint_mod(a, acount, b, bcount)
{
    var i,j,k,temp1,count;
    var result = [];
    var resultTemp = [];
    var resultTemp2 = [];
    var resultTemp3 = [];
    var resultLocal = [];
    var tempcount = 0;
    var resultcount = 0;
    var str = "";
    if(acount > bcount)
    {
        resultcount = acount;
    }
    else{
        resultcount = bcount;
    }
    
    //set result=0
    for(i=0;i<resultcount;i++)
    {
        result[i] = 0;
    }
    
    for(i = 0;i < acount;i++)
    {
        //ans = (int)(((long long)ans * 10 + n[i] - ‘0‘) % m);
        //result * 256
        for(j=0;j<resultcount-1;j++)
        {
            resultTemp[j] = result[j+1];
        }
        resultTemp[resultcount-1] = 0;
        //+a[i]
        resultTemp2 = bigint_add(resultTemp,resultcount, [a[i]], 1);
        tempcount = resultcount+1;//equal to resultTemp2.length
        
        temp1 = bigint_compare(resultTemp2, tempcount, b, bcount);
        j = 0;
        while(temp1 > 0)
        {
            //result = result - b   
            if(j == 0)
            {
                resultLocal = bigint_sub(resultTemp2, tempcount, b, bcount);
                temp1 = bigint_compare(resultLocal, tempcount, b, bcount);
                j = 1;
            }
            else
            {
                resultTemp2 = bigint_sub(resultLocal, tempcount, b, bcount);
                temp1 = bigint_compare(resultTemp2, tempcount, b, bcount);
                j = 0;
            }
        }        
        //copy result to result
        if(j == 0)
        {
            for(k=0;k<resultcount;k++)
            {
                result[resultcount-1-k] = resultTemp2[tempcount-1-k];
            }            
        }else{
            for(k=0;k<resultcount;k++)
            {
                result[resultcount-1-k] = resultLocal[tempcount-1-k];
            } 
        }
        alert("round:"+(i+1)+" "+result);
        //str
        //alert();
    }


    return result;
}

mod

标签:mod   @param   大于等于   oca   ret   for   公式   大于   return   

原文地址:https://www.cnblogs.com/yipianchuyun/p/12105338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!