加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

SGU - 112 - ab-ba (大数高精度)

发布时间:2020-12-14 02:43:48 所属栏目:大数据 来源:网络整理
导读:112. a b -b a time limit per test: 0.25 sec.? memory limit per test: 4096 KB You are given natural numbers a and b. Find a b -b a . Input Input contains numbers a and b (1≤a,b≤100). Output Write answer to output. Sample Input 2 3 Sample

112. ab-ba

time limit per test: 0.25 sec.?
memory limit per test: 4096 KB

You are given natural numbers a and b. Find ab-ba.

Input

Input contains numbers a and b (1≤a,b≤100).

Output

Write answer to output.

Sample Input

2 3

Sample Output

-1






思路:大数高精度,比较简单的一道大数题,就是写起来比较麻烦,也好久没写大数的题了,写来感受感受。。


AC代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

int a[505],b[505],ans[505];

void fun(int x,int a[]) {
	int t = x,i = 0;
	while(t) {
		a[i++] = t % 10;
		t /= 10;
	}
}

void multi(int a[],int x) {
	int up = 0;
	for(int i = 0; i < 500; i++) {
		int t = a[i] * x;
		a[i] = (t + up) % 10;
		up = (t + up) / 10;
	}
} 

void sub(int a[],int b[]) {
	int down = 0;
	for(int i = 0; i < 500; i++) {
		if(a[i] - down >= b[i]) {
			a[i] = a[i] - down - b[i];
			down = 0;
		}
		else {
			a[i] = a[i] - down - b[i] + 10;
			down = 1;
		}
	}
	
	for(int i = 500,flag = 0; i >= 0; i--) {
		if(a[i] != 0) {
			flag = 1;
			printf("%d",a[i]);
		}
		else if(a[i] == 0 && flag) printf("0");
	}
	printf("n");
}

void subtraction(int a[],int b[]) {
	int flag = 0;
	for(int i = 500; i >= 0; i--) {		//比较a的b次方和b的a次方的大小,用大的减去小的 
		if(a[i] > b[i]) {
			flag = 1; break;
		}
		else if(a[i] < b[i]) {
			flag = 2; break;
		}
	}
	if(flag == 1) {
		sub(a,b);
	}
	else if(flag == 2) {
		printf("-");
		sub(b,a);
	}
} 

int main() {
	int A,B;
	while(scanf("%d %d",&A,&B) != EOF) {
		memset(a,sizeof(a));
		memset(b,sizeof(b));
		fun(A,a),fun(B,b);	//存入数组 
		for(int i = 1; i < B; i++) {	//a的b次方 
			multi(a,A);
		}
		
		for(int i = 1; i < A; i++) {	//b的a次方 
			multi(b,B);
		}
		
		subtraction(a,b);				//a的b次方减去b的a次方 
	}
	return 0;
} 

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读