高精度类的实现 加减乘除幂余

高精度类的实现 加减乘除幂余

from my csdn blog

信息安全原理 hw2-1

  • HW2. Large number arithmetic
    • Write a +-*/ algorithm for large integers. (10 point)
    • Implement the DH algorithm. (5 point)
// name: bigint.h
// author: amrzs
// date: 2014/03/18

#ifndef BIGINT_H
#define BIGINT_H

#include <string>

using namespace std;


class Bigint{

private:
    static const int MAX_SIZE = 500;

    int size;
    int arr[MAX_SIZE];

public:
    Bigint();
    Bigint(string &s); //initialize with a string num
    ~Bigint();

    int getSize();

    Bigint operator+(Bigint &);
    Bigint operator-(Bigint &);
    Bigint operator*(Bigint &);
    Bigint operator/(Bigint &);
    Bigint operator%(Bigint &);

    Bigint operator/(int x); 

    Bigint getPow(int n, Bigint &); //return this^n % x
    Bigint getPow(Bigint &, Bigint &);
    Bigint getPow10(int n); //return this*(10^n)

    bool operator>=(Bigint &);

    bool isOdd();
    bool equalOne();

    void clear();

    void printNum();
};

#endif // BIGINT_H
// name: bigint.cpp
// author: amrzs
// date: 2014/03/18

#include <cstring>
#include <iostream>

#include "bigint.h"

using namespace std;

Bigint::Bigint(){
    //make sure to be zero(0)

    clear();
}

Bigint::Bigint(string &s){

    clear();
    size = s.length();

    if (size > MAX_SIZE){
        
        //something wrong
        cout << "too many numbers" << endl;
    }

    for (int i = size-1; i >= 0; i--)
        arr[i] = s[size-i-1] - '0';        
}

Bigint::~Bigint(){

    //to do sth    
}

int Bigint::getSize(){

    return size;
}


Bigint Bigint::operator+(Bigint &x){

    Bigint result;

    result.size = max(size, x.size);
    for (int i = 0; i < result.size; i++)
        result.arr[i] = arr[i] + x.arr[i];
    for (int i = 0; i < result.size; i++)
        if (result.arr[i] > 9){
            result.arr[i+1] += result.arr[i] / 10;
            result.arr[i] %= 10;
        }

    if(result.size > MAX_SIZE){
        cout << "Out of range in operator+" << endl;
    }

    return result;
}

Bigint Bigint::operator-(Bigint &x){

    Bigint result = *this;
    
    for (int i = 0; i < x.size; i++)
        result.arr[i] = arr[i] - x.arr[i];
    for (int i = 0; i < result.size; i++)
        if (result.arr[i] < 0){
            result.arr[i] += 10;
            result.arr[i+1]--;
        }

    while(result.size > 1 && 0 == result.arr[result.size-1])    
        result.size--;

    return result;
}

Bigint Bigint::operator*(Bigint &x){

    Bigint result;

    result.size = size + x.size - 1;
    if(result.size > MAX_SIZE){
        cout << "Out of range in operator*" << endl;
    }
    for (int i = 0; i < size; i++)
        for (int j = 0; j < x.size; j++){
            result.arr[i+j] += arr[i] * x.arr[j];
            if (result.arr[i+j] > 9){
                result.arr[i+j+1] += result.arr[i+j] / 10;
                result.arr[i+j] %= 10;
            }
        }
    if (result.arr[result.size] > 0)
        result.size++;        

    return result;
}

Bigint Bigint::operator/(Bigint &x){

    Bigint result;    
    
    if(size < x.size)
        return result;
    
    Bigint y = *this, z;    
    int pow = y.size - x.size;
    while(y >= x){
        z = x.getPow10(pow);
        while(y >= z){
            y = y - z;
            result.arr[pow]++;
        }
        pow--;
    }

    result.size = size - x.size + 1;
    while(result.size > 1 && 0 == result.arr[result.size-1])
        result.size--;

    return result;
}

Bigint Bigint::operator/(int x){

    Bigint result;
    int tmp = 0;

    for(int i = size-1; i >= 0; i--){
        tmp = tmp * 10 + arr[i];
        result.arr[i] = tmp / x;
        tmp %= x;
    }
    
    result.size = size;
    while(result.size > 1 && 0 == result.arr[result.size-1])
        result.size--;

    return result;
}

Bigint Bigint::operator%(Bigint &x){

    Bigint t = *this / x * x;    

    return *this - t; 
}

Bigint Bigint::getPow(int n, Bigint &x){

    if(n < 1){
        cout << "Parameter out of range in operator^" << endl;
    }

    if(1 == n){
        return *this % x;
    }

    Bigint t = getPow(n/2, x);

    Bigint result = t * t % x;
    if(1 == n%2){
        result = *this * result % x;
    } 

    return result;
}

Bigint Bigint::getPow(Bigint &n, Bigint &x){

    if(n.equalOne()){
        return *this % x;
    }

    Bigint nDiv2 = n / 2;
    Bigint t = getPow(nDiv2, x);

    Bigint result = t * t % x;
    if(n.isOdd()){
        result = *this * result % x;
    }

    return result;
}

Bigint Bigint::getPow10(int n){

    if(size+n >= MAX_SIZE || n < 0)
        cout << "Out of range" << endl;

    Bigint x;

    for(int i = 0; i < size; i++)
        x.arr[i+n] = arr[i];
    x.size = size + n;

    return x;
}

bool Bigint::operator>=(Bigint &x){

    if(size < x.size)
        return false;
    
    if(size == x.size){
        for(int i = size-1; i >= 0; i--)
            if(arr[i] > x.arr[i])
                return true;    //greater
            else if(arr[i] < x.arr[i])
                return false;
        return true;    //equal
    }

    return true; //greater
}

bool Bigint::isOdd(){

    return (arr[0] & 1);
}

bool Bigint::equalOne(){

    return (1==size && 1==arr[0]);
}

void Bigint::clear(){

    size = 1;
    memset(arr, 0, sizeof(*arr) * MAX_SIZE);
}

void Bigint::printNum(){

    for (int i = size-1; i >= 0; i--)
        cout << arr[i];
    cout << endl;
}
// name: main.cpp
// author: amrzs
// date: 2014/03/18

#include <string>
#include <iostream>

#include "bigint.h"

using namespace std;

Bigint calc(Bigint a, Bigint b, char c){

    Bigint result;
    switch(c){
        case '+':
            result = a + b;
            break;
        case '-':
            result = a - b;
            break;
        case '*':
            result = a * b;
            break;
        case '/':
            result = a / b;
            break;
        case '%':
            result = a % b;
            break;
        default:
            cout << "You input a wrong operator" << endl;
            break;
    }
    
    return result;
}


int main(){

    cout <<"Please input a expression like 123456789 * 987654321"
        <<"if DH then like 123456789 ^ 987654321 % 123456789" << endl;
    
    string s1, s2, s3;
    char ch1, ch2;

    while(true){ // don't like for(;;)
        
        cin >> s1 >> ch1 >> s2;
        if("quit" == s1){
            break;
        }

        Bigint a(s1), b(s2), result;        

        if('^' == ch1){         //for DH 
            cin >> ch2 >> s3;
            Bigint c(s3);
            result = a.getPow(b, c);
        }else{                  //normal expression
            result = calc(a, b, ch1);
        }

        result.printNum();
    }

    return 0;
}

Makefile:

CPP = g++
OFLAG = -o
TARGET = a.out
OBJS = main.o bigint.o

$(TARGET): $(OBJS)
    $(CPP) $(OFLAG) $(TARGET) $(OBJS)
main.o: main.cpp bigint.o
bigint.o: bigint.cpp

.PHONY: clean
clean:
    -rm $(TARGET) $(OBJS)

不足

  • 以前写高精度,总是函数方式,当然这样不妥当,我都是将最低位放在arr[1]中,而这次是放在arr[0]中,这样造成了一些细微的差别使得程序写的时候发生了一些小问题

  • 要考虑到类的数组中没有清0这件事情,我总觉得清0不好,因为效率么,当然这就带来了编程的复杂性,总是被数组里的垃圾数据干扰,出现很多错误,使得11号写的程序13号才总算完成,以后的话,我宁愿降低一些效率,使程序逻辑简单一些

  • 学了一下gdb,发现听不错的,clang++和g++在调试的时候有些区别,最好还是用g++来调试程序,当然,生成可执行文件g++和clang++都不错,主要clang++的错误提示信息很友好

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,660评论 0 33
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 如果你点了一份意大利肉酱面,发现里面没有红橙橙的番茄酱时,有以下两种可能: 一、厨房里的番茄酱刚好用完了 二、这是...
    NoBlackCoffee阅读 425评论 0 4
  • 构造函数模式、混合模式、模块模式、工厂模式、单例模式、发布订阅模式的范例 . . . . . 具体实现 Demo[...
    Carlmac阅读 177评论 0 0
  • 从来没写过泛型方法,这次项目中用到了。泛型方法理解:(1)对比泛型类,List<E>,我的理解是:泛型为了防止不必...
    ltjxwxz阅读 270评论 0 0