zoukankan      html  css  js  c++  java
  • Algorithm Gossip (16) 超长整数运算(大数运算)

    前言

    This Series aritcles are all based on the book 《经典算法大全》; 对于该书的所有案例进行一个探究和拓展,并且用python和C++进行实现; 目的是熟悉常用算法过程中的技巧和逻辑拓展。

    提出问题

    16.Algorithm Gossip: 超长整数运算(大数运算)

    分析和解释

    代码

    void add(int *a, int *b, int *c) {
        int i, carry = 0;
        for(i = N - 1; i >= 0; i--) {
            c[i] = a[i] + b[i] + carry;
            if(c[i] < 10000)
                carry = 0;
            else { // jinwei
                c[i] = c[i] - 10000;
                carry = 1;
                }
            }
        }
    void sub(int *a, int *b, int *c) {
        int i, borrow = 0;
        for(i = N - 1; i >= 0; i--) {
            c[i] = a[i] - b[i] - borrow;
            if(c[i] >= 0)
                borrow = 0;
            else { // jiewei
                c[i] = c[i] + 10000;
                borrow = 1;
                }
            }
        }
    void mul(int *a, int b, int *c) { // b is x
        int i, tmp, carry = 0;
        for(i = N - 1; i >=0;i--) {
            tmp = a[i] * b + carry;
            c[i] = tmp % 10000;
            carry = tmp / 10000;
            }
        }
    void div(int *a, int b, int *c) { 
        int i, tmp, remain = 0;
        for(i = 0; i < N;i++) {
            tmp = a[i] + remain;
            c[i] = tmp / b;
            remain = (tmp % b) * 10000;
            }
        }

    拓展和关联

    大数运算问题是经常面试考到的问题, 同样也有很多类似的问题需要我们去发现总结, 在后面有空会对这部分进行深入学习, 很多小型的计算器应用都运用了这些小算法。

    后记

    参考书籍

    • 《经典算法大全》
    • 维基百科
  • 相关阅读:
    pytest实现参数化(@pytest.mark.parametrize)
    pytest标记测试用例为预期失败(@pytest.mark.xfail)
    pytest标记跳过某些测试用例不执行
    pytest的conftest.py配置
    pytest之fixture使用
    模拟赛42 题解
    模拟赛41 题解
    一些可能永远用不到的性质
    补锅
    骗分杂谈
  • 原文地址:https://www.cnblogs.com/actanble/p/6713400.html
Copyright © 2011-2022 走看看