Ultraviolet A 10692-huge Mod (number theory)

Source: Internet
Author: User
Ultraviolet A 10692-huge mod

Question Link

Question: PleaseA0A1A2...MOD M

Idea: it is certainly not possible to calculate it directly. Use the Euler's theorem.AB=A(B MOD PHI(M) +PHI(M))(B> =PHI(M). Then, we can use the fast power to calculate the exponential value, and the calculation process is recursive.

Code:

#include <stdio.h>#include <string.h>const int N = 1005;int phi[N * 10], vis[N * 10], m, n, a[N];char M[15];int pow_mod(int x, int k, int mod) {int now = 1;for (int i = 0; i < k; i++) {if (x == 1) break;now *= x;if (now >= mod) break; } if (now >= mod) now = mod; else now = 0;if (k == 0) return 1;int ans = pow_mod(x * x % mod, k>>1, mod);if (k&1) ans = ans * x % mod;return ans + now;}int dfs(int i, int mod) {if (i == n - 1) { if (a[i] >= mod)   return a[i] % mod + mod;      return a[i];}int k = dfs(i + 1, phi[mod]);return pow_mod(a[i], k, mod);}int main() {for (int i = 1; i <= 10000; i++)phi[i] = i;for (int i = 2; i <= 10000; i++) {if (vis[i]) continue;for (int j = i; j <= 10000; j += i) {phi[j] = phi[j] / i * (i - 1);vis[j] = 1;  } } int cas = 0;while (~scanf("%s", M) && M[0] != '#') { sscanf(M, "%d", &m); scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); printf("Case #%d: %d\n", ++cas, dfs(0, m) % m); }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.