Ultraviolet A 1069-always an integer (number theory)

Source: Internet
Author: User
1069-always an integer
Given a polynomial, determine whether it is always an integer.
Idea: the example in the lrj White Paper shows that as long as the equation 1 to k + 1 (k is the maximum number of times) is an integer, then the entire equation is an integer, after the string is processed, it is computed using a fast power to determine whether the final answer is 0 and whether all the values are integers.
Code:
#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;}


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.