Not Only Algorithm,不仅仅是算法,关注数学、算法、数据结构、程序员笔试面试以及一切涉及计算机编程之美的内容 。。
你的位置:NoAlGo博客 » 题解 » 

PAT 1010. Radix

Given a pair of positive integers, for example, 6 and 110, can this equation 6 = 110 be true? The answer is "yes", if 6 is a decimal number and 110 is a binary number.

Now for any pair of positive integers N1 and N2, your task is to find the radix of one number while that of the other is given.

Input Specification

Each input file contains one test case. Each case occupies a line which contains 4 positive integers:
N1 N2 tag radix
Here N1 and N2 each has no more than 10 digits. A digit is less than its radix and is chosen from the set {0-9, a-z} where 0-9 represent the decimal numbers 0-9, and a-z represent the decimal numbers 10-35. The last number "radix" is the radix of N1 if "tag" is 1, or of N2 if "tag" is 2.

Output Specification

For each test case, print in one line the radix of the other number so that the equation N1 = N2 is true. If the equation is impossible, print "Impossible". If the solution is not unique, output the smallest possible radix.

Sample Input 1

6 110 1 10

Sample Output 1

2

Sample Input 2

1 ab 1 2

Sample Output 2

Impossible

解答

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

inline long long c2i(char c) { return c>='0' && c<='9' ? c-'0' : c-'a'+10; }

long long s2ll(char *s, long long r)
{
	long long ret = 0;
	for (int i = 0; s[i]; i++) ret *= r, ret += c2i(s[i]);
	return ret;
}

int main()
{
	char sa[11], sb[11];
	long long tag, r;

	scanf("%s%s%lld%lld", sa, sb, &tag, &r);

	if(tag == 2)
	{
		char tem[11]; strcpy(tem, sa); strcpy(sa, sb); strcpy(sb, tem);
	}

	long long a = s2ll(sa, r);

	long long mn = 2, mx = 2; //二分查找上下界
	for (int i = 0; sb[i]; i++) mn = max(mn, c2i(sb[i])+1);
	while (s2ll(sb, mx) < a) mx <<= 1;

	while (mn < mx)
	{
		long long mid = mn + ((mx - mn) >> 1);
		if (s2ll(sb, mid) >= a) mx = mid;
		else mn = mid + 1;
	}

	if (s2ll(sb, mn) == a) printf("%lld\n", mn);
	else printf("Impossible\n");

	return 0;
}
上一篇: 下一篇:

我的博客

NoAlGo头像编程这件小事牵扯到太多的知识,很容易知其然而不知其所以然,但真正了不起的程序员对自己程序的每一个字节都了如指掌,要立足基础理论,努力提升自我的专业修养。

站内搜索

最新评论