PTA乙级1006~1010【c++】
1006 换个格式输出整数
#include <iostream>
using namespace std;
int main(){
int n;
cin >> n;
int b = n / 100;
int s = n / 10 % 10;
int g = n % 10;
for (int i = 0; i < b; i ++ ) cout << 'B';
for (int i = 0; i < s; i ++ ) cout << 'S';
for (int i = 0; i < g; i ++ ) cout << i + 1;
return 0;
}
1007 素数对猜想
#include <iostream>
using namespace std;
const int N = 1e5 + 10;
bool st[N];
int p[N], cnt, res;
//素数筛
void get_prime(int n){
for (int i = 2; i <= n; i ++ ){
if (!st[i]){
p[cnt ++ ] = i;
if (cnt > 1 && p[cnt - 1] - p[cnt - 2] == 2) res ++;
}
for (int j = 0; p[j] <= n / i; j ++ ){
st[p[j] * i] = true;
if (i % p[j] == 0) break;
}
}
}
int main(){
int n;
cin >> n;
get_prime(n);
cout << res;
return 0;
}
其实没必要,纯纯暴力也能过:(如下)
#include <iostream>
using namespace std;
bool is_prime(int n){
for (int i = 2; i <= n / i; i ++ ){
if (n % i == 0) return false;
}
return true;
}
int main(){
int n, t = 3, res = 0;
cin >> n;
for (int i = 3; i <= n; i ++ ){
if (is_prime(i)){
if (i - t == 2) res ++;
t = i;
}
}
cout << res << endl;
return 0;
}
1008 数组元素循环右移问题
不移动数组的版本:
#include <iostream>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
m %= n;
int a[n];
for (int i = 0; i < n; i ++ ) cin >> a[i];
for (int i = n - m; i < n; i ++ ) cout << a[i] << ' ';
for (int i = 0; i < n - m; i ++ ){
if (i == n - m - 1) cout << a[i] << endl;
else cout << a[i] << ' ';
}
return 0;
}
老老实实移动数组的版本:
#include <iostream>
#include <algorithm>
using namespace std;
int main(){
int n, m;
cin >> n >> m;
m %= n;
int a[n];
for (int i = 0; i < n; i ++ ) cin >> a[i];
reverse(a, a + n);
reverse(a, a + m);
reverse(a + m, a + n);
for (int i = 0; i < n - 1; i ++ ) cout << a[i] << ' ';
cout << a[n - 1];
return 0;
}
用队列的版本:
#include <iostream>
#include <queue>
using namespace std;
int main(){
int m, n;
cin >> n >> m;
m %= n;
queue<int> q;
for (int i = 0; i < n; i ++ ){
int t;
cin >> t;
q.push(t);
}
if (m){
for (int i = 0; i < n - m; i ++ ){
int t = q.front();
q.pop();
q.push(t);
}
}
while (q.size() > 1){
cout << q.front() << ' ';
q.pop();
}
cout << q.front();
return 0;
}
1009 说反话
温馨提示:循环输入按Ctrl+Z结束输入
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int main(){
stack<string> S;
string t;
while (cin >> t) S.push(t);
while (S.size() > 1){
cout << S.top() << ' ';
S.pop();
}
cout << S.top();
return 0;
}
1010 一元多项式求导
#include <iostream>
using namespace std;
int main(){
int n, m;
bool flag = false;
while(cin >> n >> m){
if (flag && m && n) cout << ' ';
if (!m || !n) continue;
else{
cout << n * m << ' ' << m - 1;
flag = true;
}
}
if (!flag) cout << "0 0";
return 0;
}