大数模板未验证

72 阅读1分钟

自己写的大数加法乘法除法,挺费时间

#include<iostream>
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
char sa[100], sb[100];
struct node{
	int m[9000];
	int po;
};
int yu;
void dis(node a){
	cout<<"结果"<<endl;
	for(int i = a.po; i>=0; i--)
		cout<<a.m[i];
	cout<<endl;
}

nnode mul(node s1, node s2){  
    node te;                        //结构体没有初始化非常的危险,数组里面的数都是随机的,大部分为0,最好在构造函数里面初始
    if(s2.po == -1)
    	s2.m[0] = 1;
    memset(te.m, 0, sizeof(te.m));  
    //int ob;
    for(int i = 0; i <= s1.po; i++)  
        for(int j = 0; j <= s2.po; j++){  
           te.m[i + j] += s1.m[i] * s2.m[j];  
        }   
    te.po = s1.po + s2.po;  
    //ob = 0;
    for(int i = 0; i <= te.po; i++){  
       
		if(te.m[i] > 9){  
            te.m[i + 1] += te.m[i] / 10;  
            te.m[i] = te.m[i] % 10;   
        }  
    }  
    
    if(te.m[te.po+1] > 0)  
        te.po++;
		 
	return te;  
} 
node divi(node a, int x){
  node te;
  if(x == 0){
  	te.m[0] = 0;
  	te.po = 0;
  	return te;
  } 
  
  int cnt = 0, ans = 0, ju ;
  

  for(int i = a.po; i >= 0; i--){
  	  ans = ans * 10 + a.m[i];
	  if(ans < x){
	    te.m[cnt++] = 0;
	  	continue;
	  }
	  te.m[cnt++] = ans / x;
	  ans = ans % x;
	  
  }
    for(ju = 0; te.m[ju]  == 0; ju++)
        ;
  
   for(int i = ju; i < cnt; i++)
   		cout<<te.m[i];
  cout<<endl;
  cout<<"剩余"<<ans<<endl;
  
  node fe;
 
   for(int i = 0; i < cnt- ju; i++)
   		fe.m[i] = te.m[cnt - 1 - i];
   		
   fe.po = cnt - ju - 1;
   
   for(int i = 0; i <= fe.po; i++)
   			cout<<fe.m[i];
   	cout<<endl;
   
   return fe;
  
  
}
node add(node a, node b){
	int len = max(a.po, b.po);

	node te;
	memset(te.m, 0, sizeof(te.m));
	
	for(int i = 0; i <= len; i++) 
	     te.m[i]=a.m[i] + b.m[i];
	   
	for(int i = 0; i <= len; i++){
		if(te.m[i] > 9){
		    te.m[i + 1] += te.m[i] / 10;
			te.m[i] = te.m[i] % 10;	
		}
	}
	te.po = len;
	if(te.m[len + 1] != 0)
	  te.po++;
	  
	dis(te);
	  
	return te;
	
} 

int main(){
	while(1){
		int x;
		scanf("%s%s",sa,sb);
		//scanf("%s%d", sa, &x);
		
		int la = strlen(sa), lb = strlen(sb);
		node s1, s2;
		memset(s1.m, 0, sizeof(s1.m));
		memset(s2.m, 0, sizeof(s2.m));
		
		for(int i = 0; i < la; i++){
			s1.m[i] = sa[la - 1 - i] - '0';
		}
		s1.po = la - 1;
		
		for(int i = 0; i < lb; i++){
			s2.m[i] = sb[lb - 1 - i] - '0';
		}
		s2.po = lb - 1;
	
	//mul(s1, s2);
	//divi(s1, x);
	add(s1,s2);
	}
	
	return 0;
} 


\

本文已参与「新人创作礼」活动,一起开启掘金创作之路