UVa Problem Solution: 10006 - Carmichael Numbers


Compute the remainder with the following equation:
    (x*y)%n = (x%n)*(y%n)%n

Code:
  1. /***************************************************************************
  2.  *   Copyright (C) 2008 by Liu Kaipeng                                     *
  3.  *   LiuKaipeng at gmail dot com                                           *
  4.  ***************************************************************************/
  5. /* @JUDGE_ID 00000 10006 C++ "Carmichael Numbers" */
  6. #include <algorithm>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <deque>
  10. #include <fstream>
  11. #include <iostream>
  12. #include <list>
  13. #include <map>
  14. #include <queue>
  15. #include <set>
  16. #include <stack>
  17. #include <string>
  18. #include <vector>
  19. using namespace std;
  20.      
  21. int const max_num = 65001;
  22. bool is_prime[max_num];
  23. void gen_primes()
  24. {
  25.   for (int i = 0; i < max_num; ++i)
  26.     is_prime[i] = true;
  27.   for (int i = 2; i < max_num; ++i) {
  28.     for (; i < max_num && !is_prime[i]; ++i) {}
  29.     for (int j = 2; i*j < max_num; ++j)
  30.       is_prime[i*j] = false;
  31.   } 
  32. }
  33. /*
  34.  * Calculate a^n % n with a divide and conquer method
  35.  */
  36. int power_mod(int a, int p, int n)
  37. {
  38.   if (p == 1) return a;
  39.   unsigned int r = power_mod(a, p/2, n);
  40.   if (p % 2 == 0) {
  41.     return r * r % n;
  42.   } else {
  43.     r = r * r % n;
  44.     return r * a % n;
  45.   }
  46. }
  47. bool is_carmichael(int n)
  48. {
  49.   if (is_prime[n]) return false;
  50.   for (int a = 2; a < n; ++a) {
  51.     if (power_mod(a, n, n) != a) return false;
  52.   }
  53.   return true;
  54. }
  55.           
  56. int main(int argc, char *argv[])
  57. {
  58. #ifndef ONLINE_JUDGE
  59.   freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
  60.   freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
  61. #endif
  62.   
  63.   gen_primes();
  64.   for (int n; cin >> n && n != 0; )
  65.     if (is_carmichael(n)) 
  66.       cout << "The number " << n << " is a Carmichael number./n";
  67.     else
  68.       cout << n << " is normal./n";
  69.   return 0;
  70. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值