3234. 组素数
素数就是不能再进行等分的数。比如:2 3 5 7 11 等。
9 = 3 * 3 说明它可以3等分,因而不是素数。
我们国家在1949年建国。如果只给你 1 9 4 9 这4个数字卡片,可以随意摆放它们的先后顺序(但卡片不能倒
着摆放啊,我们不是在脑筋急转弯!),那么,你能组成多少个4位的素数呢?
比如:1949,4919 都符合要求。
请你提交:能组成的4位素数的个数,不要罗列这些素数!!
错误原因:全排列next_permutation()默认从小到大排列,而自己第一个字符串设置的1949,运行时会自动忽略1499这个较小的数字,而1499又是素数,所以得出的答案是5个,而不是6个。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <string>
#include <cmath>
using namespace std;
int isPrime(int n) {
if (n <= 1)
return 0;
if (n == 2 || n == 3)
return 1;
if (n % 6 != 1 && n % 6 != 5)
return 0;
for (int i = 5; i <= (int)sqrt(n); i += 6)
if (!(n % i) || !(n % (i+2)))
return 0;
return 1;
}
int str_int(string s) {
int len = s.length();
int sum = 0;
for (int i = len - 1; i >= 0; i--) {
sum = sum * 10 + (int)(s[i]-'0');
}
return sum;
}
int main(void) {
string s = "1499"; // 错误原因:string s = "1949"
int cnt = 0;
do {
if (isPrime(str_int(s)))
cnt++;
} while (next_permutation(s.begin(), s.end()));
cout << cnt << endl;
return 0;
}