UVa Problem 10042 Smith Numbers (Smith 數)

來源:互聯網
上載者:User
// Smith Numbers (Smith 數)// PC/UVa IDs: 110706/10042, Popularity: B, Success rate: average Level: 1// Verdict: Accepted// Submission Date: 2011-06-10// UVa Run Time: 0.060s//// 著作權(C)2011,邱秋。metaphysis # yeah dot net//// 對數進行素因子分解即可。因為所求數小於 10E9,若某數是合數,則其素因子至少有一個小於或等於// sqrt(10E9),則可先計算 2 - sqrt(10E9) 之間的素數以備用。#include <iostream>#include <vector>#include <cmath>#include <ctime>using namespace std;#define UPBOUND 31623// ceil(sqrt(10E9))vector < int > prime;// 儲存 2 - ceil(sqrt(10E9)) 之間的素數,方便解題。// 判斷數 n 是否是素數。bool is_prime(int n){if (n == 2)return true;if (n % 2 == 0)return false;for (int c = 3; c <= ceil(sqrt(n)); c += 2)if (n % c == 0)return false;return true;}// 預先產生 2 - ceil(sqrt(10E9)) 之間的素數。void find_prime(){prime.push_back(2);for (int c = 3; c < UPBOUND; c += 2)if (is_prime(c))prime.push_back(c);}// 計算數 number 的數位之和。int digits_sum(int number){int sum = 0;while (number){sum += (number % 10);number /= 10;}return sum;}void smith(int number){int current = number + 1;while (1){// 如果是素數,不是 Smith 數。if (is_prime(current)){current++;continue;}// 計算數 current 的數位元字之和。int tmp = current;int sum = digits_sum(current), tsum = 0;// 計算數 current 的素因子之和。while (1){int memo = tmp;for (int c = 0; c < prime.size(); c++)if (tmp % prime[c] == 0){tmp /= prime[c];tsum += digits_sum(prime[c]);break;}// 若 tmp 為 1,表明找到了所有的素因子,若 tmp 未變化,則表明在// 2 - sqrt(10E9) 之間已經沒有 tmp 的素因子存在,則 tmp 必定// 是一個素數。if (tmp == 1 || memo == tmp)break;}// 此時若 tmp 不為 1,則必定是素數,因為若是合數,在 2 - sqrt(10E9) 之間// 都沒有它的素因子,這是不可能的,若這樣,該數的素因子都大於sqrt(10E9),則// 該數必定大於 10E9,與題目條件不符合。if (tmp > 1)tsum += digits_sum(tmp);// 判斷素因子和與數位和是否相等。if (tsum == sum){cout << current << endl;break;}current++;}}int main(int ac, char *av[]){int cases, number;find_prime();cin >> cases;while (cases--){cin >> number;smith(number);}return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.