programming-challenges Smith Numbers (110706) 题解

nothing special

#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <map>
#include <set>
#include <stack>
#include <assert.h>
#include <algorithm>
#include <math.h>
#include <ctime>
#include <functional>
#include <string.h>
#include <stdio.h>
#include <numeric>
#include <float.h>

using namespace std;

const int PRIMESIZE = 32000;
vector<int> primes; 

void getPrimes() {
	vector<bool> visited(PRIMESIZE);
	int sq = sqrt((double)PRIMESIZE);

	for (int i = 2; i <= sq; i++) {
		if (!visited[i]) {
			primes.push_back(i);
			for (int j = i + i; j < PRIMESIZE; j+=i) {
				visited[j] = true;
			}
		}
	}
	for (int i = sq + 1; i < PRIMESIZE; i++)
		if (!visited[i]) primes.push_back(i);
}

int getNumberSum(int num) {
	int result = 0;

	while (num >= 10) {
		result += (num % 10); 
		num /= 10; 
	}

	return result + num; 
}

int primeFactorSum(int num) {
	int result = 0; 
	int sq = sqrt(num); 
	int factorNum = 0; 
	for (int i = 0; i < primes.size(); i++) {
		if (primes[i] > num) break;
		while (num % primes[i] == 0) {
			factorNum++; 
			result += getNumberSum(primes[i]);
			num /= primes[i]; 
		}
	}
	if (num > 1) {
		factorNum++;
		result += getNumberSum(num);
	}
	if (factorNum == 1) return -1; 
	return result; 
}

int main() {
	getPrimes();
	int tc = 0; cin >> tc; 
	for (int i = 0; i < tc; i++) {
		int num = 0; cin >> num; 
		do {
			num++; 
			if (getNumberSum(num) == primeFactorSum(num)) {
				cout << num << endl; 
				break;
			}
		} while (true);

	}

	return 0; 
}


你可能感兴趣的:(Algorithm,C++)