1. 程式人生 > >「學習筆記」C++ 高精度演算法

「學習筆記」C++ 高精度演算法

高精度演算法解決long long也解決不了的計算

高精度的儲存是把每一位單獨儲存,且是倒序儲存,陣列num[1]是這個數的個位,num[2]是這個數的十位,以此類推;

(一)高精度加法

#include <iostream>
#include <cstring>
using namespace std;

struct HugeInt{
	int len;
	int num[100001];
}; 

HugeInt a, b, w;        //w為結果 
char c[100001], d[100001];

void Scan_HugeInt() {   //讀入兩個大整數 
	cin >> c;
	cin >> d;
	a.len = strlen(c); //strlen求串長 
	b.len = strlen(d);
	for(int i=0; i<a.len; i++) a.num[a.len - i] = c[i] - '0'; //逆序儲存 
	for(int i=0; i<b.len; i++) b.num[b.len - i] = d[i] - '0';
}

void Plus() {
	w.len = max(a.len, b.len);           //num每一位是0,長度取max不影響加法 
	for(int i=1; i<=w.len; i++) {
		w.num[i] += a.num[i] + b.num[i]; 
		w.num[i+1] += w.num[i] / 10;    //處理進位
		w.num[i] %= 10;                 //處理當前位 保證<10 
	}
	if(w.num[w.len + 1] != 0) w.len ++;  //加法最多有可能會多出一位 
}

int main() {
	Scan_HugeInt();
	Plus();
	for(int i=w.len; i>=1; i--) cout << w.num[i]; //倒序儲存 倒序輸出 
	cout << endl;
	return 0;
}

(二)高精度減法

#include <iostream>
#include <cstring>
using namespace std;

struct HugeInt {
	int len;
	int num[100001];
};

HugeInt a, b, w;         //w為結果
char c[100001], d[100001];
bool negative;           //負數標記 

void Scan_HugeInt() {    //讀入兩個大整數
	cin >> c;
	cin >> d;
	if((strlen(c) < strlen(d)) || (strlen(c) == strlen(d) && strcmp(c, d) < 0)) { //若被減數小 交換 記為負數 
		negative = true;
		swap(c, d);
	}
	a.len = strlen(c);
	b.len = strlen(d);
	for(int i=0; i<a.len; i++) a.num[a.len - i] = c[i] - '0'; 
	for(int i=0; i<b.len; i++) b.num[b.len - i] = d[i] - '0';
}

void Minus() {
	w.len = a.len;                //a更大 
	for(int i=1; i<=w.len; i++) {
		if(a.num[i] < b.num[i]) {  
			a.num[i+1] --;      //num[i+1]減成負數也不影響 
			a.num[i] += 10;     //借位 
		}
		w.num[i] += a.num[i] - b.num[i];
	}
	while(w.num[w.len] == 0 && (w.len != 1)) w.len --; //多餘的不是個位的0去掉 
}

int main() {
	Scan_HugeInt();
	Minus();
	if(negative == true) cout << "-";             //負數加負號 
	for(int i=w.len; i>=1; i--) cout << w.num[i]; //倒序儲存 倒序輸出
	cout << endl;
	return 0;
}

(三)高精度乘法

#include <iostream>
#include <cstring>
using namespace std;

struct HugeInt {
	int len;
	int num[100001];
};

HugeInt a, b, w; 
char c[10001], d[10001];

void Scan_HugeInt() {    //讀入兩個大整數
	cin >> c;
	cin >> d;
	a.len = strlen(c);
	b.len = strlen(d);
	for(int i=0; i<a.len; i++) a.num[a.len - i] = c[i] - '0';
	for(int i=0; i<b.len; i++) b.num[b.len - i] = d[i] - '0';
}

void Multiply() {
	int x;              //處理每次進位的變數 
	for(int i=1; i<=a.len; i++) {      //a的第i位 
		x = 0;
		for(int j=1; j<=b.len; j++) { //b的第j位 
			w.num[i+j-1] += a.num[i] * b.num[j] + x; //用 +=:結果與上次乘的結果相加 
			x = w.num[i+j-1] / 10;
			w.num[i+j-1] %= 10;          //進位處理 
		} 
		w.num[i+b.len] = x;  //多出的最高位 
	}
	w.len = a.len + b.len;
	while(w.num[w.len] == 0 && (w.len != 1)) w.len --; //多餘的0 
}

int main() {
	Scan_HugeInt();
	Multiply();
	for(int i=w.len; i>=1; i--) cout << w.num[i];
	cout << endl;
	return 0;
}

(四)高精度除法

除以高精時,直接列舉每一位.

除以低精時,可以使用另種模擬更快


Int1000 operator / (const int &b) { //除以低精
	if(*this < Int1000(b)) return Int1000(0);
	Int1000 ans;
	ans.len = len;
	int r = 0;
	for(int i=ans.len; i>=1; i--) {
		r = r * 10 + a[i];
		ans.a[i] = r / b;
		r %= b;
	}
	while(ans.len > 1 && !ans.a[ans.len]) ans.len --;
	return ans;
}
Int1000 operator / (Int1000 b) {
	if(*this < b) return Int1000(0);
	Int1000 ans; ans.len = len - b.len + 1;
	for(int i=ans.len; i>=1; i--) {
		for(int j=1; j<=9; j++) {
			ans.a[i] ++;
			if((*this) < (ans * b)) {
				ans.a[i] --;
				break;
			}
		}
	        if(ans.a[ans.len] == 0) ans.len --;
        }
	while(ans.len > 1 && !ans.a[ans.len]) ans.len --;
	return ans;
}

高精度模版:

PS:常數較大,謹慎使用

const int MAX_SIZE = 1010;

struct Int {
	int len, n[MAX_SIZE];
	void Set(int l) {
		len = l;
		for(int i = 1; i <= len; i ++) n[i] = 0;
	}
	Int(char *s) {
		len = strlen(s);
		for(int i = len - 1; ~i; i --) {
			if(s[i] <= '9' && s[i] >= '0') {
				len = i + 1;
				break;
			}
		}
		for(int i = len; i >= 1; i --) n[i] = s[len - i] - '0';
	}
	Int(long long x = 0) {
		len = 0;
		do {
			n[++ len] = x % 10;
			x /= 10;
		} while(x);
	}
	bool operator < (const Int b) {
		if(len != b.len) return len < b.len;
		for(int i = len; i; i --)
			if(n[i] != b.n[i]) return n[i] < b.n[i];
		return false;
	}
	Int operator + (const Int b) const {
		Int ans; ans.Set(max(len, b.len) + 1);
		for(int i = 1; i <= ans.len; i ++) {
			if(i <= len) ans.n[i] += n[i];
			if(i <= b.len) ans.n[i] += b.n[i];
			ans.n[i + 1] += ans.n[i] / 10;
			ans.n[i] %= 10;
		}
		while(!ans.n[ans.len] && ans.len > 1) ans.len --;
		return ans;
	}
	Int operator - (const Int b) {
		Int ans, a = *(this); ans.Set(len);
		for(int i = 1; i <= ans.len; i ++) {
			if(a.n[i] < b.n[i]) a.n[i + 1] --, a.n[i] += 10;
			ans.n[i] += a.n[i] - (i > b.len ? 0 : b.n[i]);
		}
		while(!ans.n[ans.len] && ans.len > 1) ans.len --;
		return ans;
	}
	Int operator * (Int b) {
		Int ans; ans.Set(len + b.len);
		for(int i = 1; i <= len; i ++) {
			for(int j = 1; j <= b.len; j ++) {
				ans.n[i + j - 1] += n[i] * b.n[j];
				ans.n[i + j] += ans.n[i + j - 1] / 10;
				ans.n[i + j - 1] %= 10;
			}
		}
		while(!ans.n[ans.len] && ans.len > 1) ans.len --;
		return ans;
	}
	Int operator / (const int &b) { //除以低精  
     	    if(*this < Int(b)) return Int(0LL);  
     	    Int ans; ans.len = len;  
     	    int r = 0;  
     	    for(int i = ans.len; i; i --) {  
     		r = r * 10 + n[i];  
     		ans.n[i] = r / b;  
          	r %= b;  
        }  
            while(ans.len > 1 && !ans.a[ans.len]) ans.len --;  
            return ans;  
        }  
	Int operator / (const Int b) {
		if((*this) < b) return Int(0LL);
		Int ans; ans.Set(len - b.len + 1);
		for(int i = ans.len; i; i --) {
			for(int j = 1; j <= 9; j ++) {
				ans.n[i] ++;
				if((*this) < (ans * b)) {
					ans.n[i] --;
					break;
				}
			}
		}
		while(ans.len > 1 && !ans.n[ans.len]) ans.len --;
		return ans;
	}
	void print() {
		for(int i = len; i; i --) 
			printf("%d", n[i]);
		printf("\n");
	}
};

黑科技:兩個long long實現高精度

typedef long long LL;
const LL Base = (LL)1e9;

struct Long {
    LL high, low;
    Long(LL x = 0) : low(x) {high = 0;}
    friend Long operator + (const Long &a, const Long &b) {
        Long c; c.high = a.high + b.high, c.low = a.low + b.low;
        if (c.high >= 0 && c.low >= Base) c.high += c.low / Base, c.low = c.low % Base;
        if (c.high <= 0 && c.low <= -Base) c.high += c.low / Base, c.low = c.low % Base;
        if (c.high > 0 && c.low < 0) c.high --, c.low += Base;
        if (c.high < 0 && c.low >= Base) c.high ++, c.low -= Base;
        return c;
    }
    friend bool operator <(const Long &a, const Long &b) {
        return a.high == b.high ? a.low < b.low : a.high < b.high;
    }
    friend Long max(const Long &a, const Long &b) {return a < b ? b : a;}
};

相關推薦

學習筆記C++ 精度演算法

高精度演算法解決long long也解決不了的計算 高精度的儲存是把每一位單獨儲存,且是倒序儲存,陣列num[1]是這個數的個位,num[2]是這個數的十位,以此類推; (一)高精度加法 #include <iostream> #includ

學習筆記C++與C++11的語法技巧

隨機打亂序列與生成隨機數。 #include <algorithm> //random_shuffle #include <cstdio> #include <random> using namespace std; int main() {

學習筆記可持久化線段樹

中位數 root lca peak 繼續 bzoj2653 進行 turn size 註:此博客寫於 2017.12 可持久化線段樹 常見的一個實現是主席樹,由HJT主席引入中國OI界。 基本思想 考慮一顆不同的線段樹,進行單點修改。註意到每一次只會修改 \(\log\

學習筆記數論函數

以及 display max 很多 chl 51nod ble 成了 time 註:此博客寫於 2017.12 Warn:此博文有超過近10處錯誤,請結合上下文辨別 前置技能 定義 數論函數。 定義域為正整數的函數。以下默認所有數都是正整數。 積性函數。 對於所有

學習筆記網絡流基礎

bzoj3996 特殊 其中 線性 一次 子集 不可 做到 二分 註:此博客寫於 2017.11 前言 今年NOIP2017提高的初賽考到的最小割。這是否意味著網絡流進入NOIP考綱? 蒟蒻Cyani發現,周圍的同學都會網絡流啊。蒟蒻也來學一學姿勢。 比較推薦LRJ的藍

c++精度演算法-大整數運算

#include<iostream> #include<vector> #include<cstring> using namespace std; struct BigInteger{ static const int BASE=100000000;

學習筆記鏈式前向星

鏈式前向星 圖的儲存一般有兩種:鄰接矩陣、前向星。 若圖是稀疏圖,邊很少,開二維陣列a[][]很浪費; 若點很多(如10000個點)a[10000][10000]又會爆.只能用前向星做.   前向星的效率不是很高,優化後為鏈式前向星,直接介紹鏈式前向星。  

學習筆記容斥原理及其應用

容斥原理 說的是一種計數方式,使得每種情況只被記一次。 ∑ i

學習筆記Fast Fourier Transform 快速傅立葉變換

快速傅立葉變換( Fast Fourier Transform,FFT \text{Fast Fourier Transfo

學習筆記李超線段樹

「學習筆記」李超線段樹 background 學這個演算法的是因為某天一個題用$ \text{ set } $維護斜率被卡常數了,在某大佬的安利下學了這個科技,聯賽後又思考了很多關於這個演算法的問題,於是寫一篇部落格來頹廢並調整一下文化課學習以來壓抑的心態。 在平時的一些訓練中往往遇到一些維護斜率的問題

[C++]精度演算法

目錄 高精度加法    高精度減法    高精度乘法    高精度除法    高精度階乘 高精度加法 用程式來模擬豎式加法即可,注意在輸出的時候除去多餘的前導零

學習筆記uoj #41 【清華集訓2014】矩陣變換

題解:有這樣一個演算法: 給定n個排列Ai和n個排列Bi,求一個排列p使得: ∀i,j∈[1,n],j≠pi,Ai,pi&lt;Ai,j∨Bk∣pk=j,j&lt;Bi,j\forall i,j\in[1,n],j\neq p_i,A_{i,p_

學習筆記進位制轉換

前言 由於本人正在準備自考,所以學習下c語言以及相關的基礎,最近會更新很基礎的知識 進位制 常用的進位制分別為2進位制、10進位制(生活常用)、16進位制 進位制間的關係表 二進位制 十進位制 十六進位制 0 0 0 1 1 1 10 2 2 11 3 3 100 4 4 1

學習筆記集合冪級數

「學習筆記」集合冪級數 本文是一篇學習筆記,具體的概念請參考2015年VFK的國家隊論文《集合冪級數的性質及其快速演算法》 集合並卷積 - 快速莫比烏斯變換 我們要求形如這樣的一個卷積: \[ h_S =\sum_{L \subseteq S}\sum_{R\subseteq S} [L\cup R=S

學習筆記斜率優化

「HNOI 2008」玩具裝箱TOY 首先O(n2)O(n^2)O(n2)做法是顯然的,使用字首和然後暴力列舉轉移 dp[0] = 0; for(int i = 1; i <= n; i ++)

學習筆記Min25篩

前言 M i n 25

學習筆記迴文樹/迴文自動機(Palindromic Tree)

引入 有時候題目要求一些這樣的問題 1. 求以串 s s s 本質不同的迴文串個數(即長度不同或長度相同且至少有一個字元不相同的字串) 2. 求以位置 i

學習筆記ISAP求最大流

ISAP學習筆記 ISAP是OI中求最大流的常用方法之一。相對於Dinic,ISAP的速度提升了很多,但編碼複雜度也上升了不少。 約定 採用鄰接表儲存圖,對於每條弧,增加一條容量為0的逆向邊。 d陣列代表每個點到終點的距離。 引入 求解最大流有一種基礎方法,每次在殘量網

C++精度演算法精度減法

高精度減法 題目描述 高精度減法 輸入 兩個整數a,b(第二個可能比第一個大) 輸出 結果(是負數要輸出負號) 樣例輸入 2 1 樣例輸出 1 說明 20%資料a,b