UVa Problem Solution: 10168 - Summation of Four Primes


According to the Goldbach's Conjecture, every even number that is not less than 4 is the sum of two primes. So we can just reduce the number to an even number by subtracting 4=2+2 or 5=2+3 from it, and then test every possible summation of the remaining two addend to see if they are both primes.

Code:
  1. /***************************************************************************
  2.  *   Copyright (C) 2008 by Liu Kaipeng                                     *
  3.  *   LiuKaipeng at gmail dot com                                           *
  4.  ***************************************************************************/
  5. /* @JUDGE_ID 00000 10168 C++ "Summation of Four Primes" */
  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. int const max_primes = 10000001;     
  21. bool primes[max_primes];
  22. void gen_primes()
  23. {
  24.   primes[0] = primes[1] = false;
  25.   for (int i = 2; i < max_primes; ++i)
  26.     primes[i] = true;
  27.   for (int i = 2; i < max_primes; ++i) {
  28.     for (; i < max_primes && !primes[i]; ++i) {}
  29.     for (int j = 2; i*j < max_primes; ++j)
  30.       primes[i*j] = false;
  31.   } 
  32. }
  33. bool sum_primes(int n, int s[])
  34. {
  35.   if (n < 8) return false;
  36.   if (n % 2 == 0) {
  37.     s[0] = s[1] = 2;
  38.     n -= 4;
  39.   } else {
  40.     s[0] = 2;
  41.     s[1] = 3;
  42.     n -= 5;
  43.   }
  44.   for (int i = 2, e = n / 2; i <= e; ++i)
  45.     if (primes[i] && primes[n-i]) {
  46.       s[2] = i;
  47.       s[3] = n - i;
  48.       return true;
  49.     }
  50.   return false;
  51. }
  52.           
  53. int main(int argc, char *argv[])
  54. {
  55. #ifndef ONLINE_JUDGE
  56.   freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
  57.   freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
  58. #endif
  59.   gen_primes();
  60.   char delim[] = "   /n";
  61.   for (int n, s[4]; cin >> n; )
  62.     if (sum_primes(n, s))
  63.       for (int i = 0; i < 4; ++i)
  64.     cout << s[i] << delim[i];
  65.     else
  66.       cout << "Impossible./n";
  67.   return 0;
  68. }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值