经典算法 - 求两个大数之和

之间在某次面试过程中遇到的,现在做一下记录

function towBigSum(str1, str2) {  
  // 求两个字符串最大的长度
  const maxLen = Math.max(str1.length, str2.length);
  
  // 在字符串头部用0补齐到最大长度
  num1_str = str1.padStart(maxLen, '0');
  num2_str = str2.padStart(maxLen, '0');
  console.log([num1_str, num2_str]);
  
  // 存储进位值的哈希对象
  const dp = [];
  let resArr = [];
  
  // 循环2个字符串,将对应位置上的数字相加
  for(let i=maxLen -1; i >=0; i--){
     const index = maxLen - i - 1; 
    
    // 对应的字符转为数字相加相加
     const plus = parseInt(num1_str.charAt(i), 10) + parseInt(num2_str.charAt(i), 10) + (dp[index] || 0);
    
    console.log(plus);
     // resArr的下标
    
    
     // 相加后的进位值存储在dp哈希表
     dp[index+1] = plus > 9 ? 1: 0;
     console.log(dp);
     resArr[index] =  plus < 10 ? plus : plus - 10;
     
       
  }
  
 
  if (dp[dp.length -1] > 0 ) {
      resArr.push(dp[dp.length - 1]);
  } 

  
  // 倒置结果集
  resArr = resArr.reverse();
  
  // 返回结果集字符串
  return resArr.join('');
  
}

// 测试
console.log(towBigSum('999', '1'));

// 最后返回
// 1000
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
以下是实现RSA公钥解密算法的Python代码,需要用到pycryptodome库中的模块: ```python from Crypto.Util import number # 素性测试算法 def is_prime(n, k=128): """ Miller-Rabin素性测试算法 """ if n <= 3: return n == 2 or n == 3 s, d = 0, n - 1 while d % 2 == 0: s += 1 d //= 2 for i in range(k): a = number.getRandomRange(2, n - 2) x = pow(a, d, n) if x == 1 or x == n - 1: continue for r in range(1, s): x = pow(x, 2, n) if x == n - 1: break else: return False return True # 优化后的大数质因子分解算法 def factorize(n): """ Pollard-Rho质因数分解算法 """ def gcd(a, b): while b: a, b = b, a % b return a def rho(n): if n % 2 == 0: return 2 x, y = number.getRandomRange(0, n - 1), 1 c = number.getRandomRange(0, n - 1) k = 2 while True: x = (pow(x, 2, n) + c) % n d = gcd(abs(x - y), n) if d != 1 and d != n: return d k -= 1 if k == 0: y = x k = 2 if x == y: c = number.getRandomRange(0, n - 1) y = 1 if n <= 3: return [n] x, y = n, n while y == n: x = rho(x) y = rho(rho(y)) p = gcd(x - y, n) if p == n: return factorize(n) return factorize(p) + factorize(n // p) # RSA公钥解密算法 def rsa_decrypt(c, N, e): """ RSA公钥解密算法 """ # 出p和q factors = factorize(N) p, q = factors[0], factors[1] # 计算d phi_N = (p - 1) * (q - 1) d = number.inverse(e, phi_N) # 解密 m = pow(c, d, N) return m # 测试 if __name__ == '__main__': N = 196520507 e = 65537 c = 177252946 m = rsa_decrypt(c, N, e) print(m) ``` 其中,is_prime()函数是实现Miller-Rabin素性测试算法,用于检验一个数是否为素数;factorize()函数是实现Pollard-Rho质因数分解算法,用于对大数进行质因数分解;rsa_decrypt()函数是实现RSA公钥解密算法,用于解密RSA加密后的密文。 测试部分给出了一个示例,使用上述代码解密RSA加密后的密文。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丢丢的大神

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值