码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 1069 - Always an integer(数论)

时间:2014-07-02 08:12:34      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:style   http   color   os   代码   for   

1069 - Always an integer


题意:给定一个多项式,判断是否总是整数

思路:LRJ大白上的例题,上面给出了证明,只要1到k + 1(k为最高次数)带入方程都是整数,那么整个方程就是整数,处理出字符串后,然后过程用快速幂计算,判断最后答案是否为0,看是否全都满足是整数。

代码:
#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

char str[105];

struct X {
	long long a, k;
} x[105];

long long mu, Max;
int xn;

void build() {
	mu = Max = 0; xn = 0;
	long long s = 0, a = 0, flag = 1, k = 0;
	int len = strlen(str);
	for (int i = 0; i < len; i++) {
		if (str[i] >= '0' && str[i] <= '9') {
			if (s == 0) a = a * 10 + str[i] - '0';
			if (s == 1) k = k * 10 + str[i] - '0';
			if (s == 2) mu = mu * 10 + str[i] - '0';
  		}
  		else if (str[i] == 'n')
  			s = 1;
		else if (str[i] == '/')
			s = 2;
		else if (str[i] == '+' || str[i] == '-' || str[i] == ')') {
			if (s >= 1) {
				if (a == 0) a = 1;
				if (k == 0) k = 1;
   			}
   			Max = max(Max, k);
   			x[xn].a = a * flag; x[xn].k = k; xn++;
   			if (str[i] == '-') flag = -1;
   			else if (str[i] == '+') flag = 1;
   			a = k = s = 0;
  		}
 	}
}

long long pow_mod(long long x, long long k) {
	long long ans = 1;
	while (k) {
		if (k&1) ans = ans * x % mu;
  		x = x * x % mu;
  		k >>= 1;
 	}
 	return ans;
}

bool judge() {
	for (long long i = 0; i <= Max + 1; i++) {
		long long ans = 0;
  		for (int j = 0; j < xn; j++) {
			ans = (ans + x[j].a * pow_mod(i, x[j].k)) % mu;
  		}
  		if (ans) return false;
 	}
 	return true;
}

int main() {
	int cas = 0;
	while (~scanf("%s", str) && str[0] != '.') {
		build();
		printf("Case %d: %s\n", ++cas, judge()?"Always an integer":"Not always an integer");
 	}
	return 0;
}


UVA 1069 - Always an integer(数论),布布扣,bubuko.com

UVA 1069 - Always an integer(数论)

标签:style   http   color   os   代码   for   

原文地址:http://blog.csdn.net/accelerator_/article/details/36252867

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!