使用网站:点此
文章目录
1. [递归]母牛的故事
2. Hello,World
#include<iostream>
using namespace std;
int main()
{
int n;
while(cin >> n)
{
printf("%c",n);
}
}
3. 用筛法求之N内的素数
数组法
#include<iostream>
using namespace std;
int isPrime(int n)
{
for(int i=2 ; i < n/2 ; i++)
{
if(n%i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
int n;
cin >> n;
int prime[n]={
0,1,1,1,0,1};
for(int i = 6 ; i < n ; i++)
{
if(isPrime(i))
{
prime[i] = 1;
}
else
{
prime[i] = 0;
int j = 2;
while(j*i < n)
{
prime[j*i] = 0;
j++;
}
}
}
for(int i=2;i<n;i++)
{
if(prime[i])
{
cout << i << endl;
}
}
}
4. 字符逆序
要点:输入空格
方法一:栈
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string a, b;
getline(cin, a);
for(int i =0; i < a.size(); i++)
{
b.push_back(a.at(a.size() - i -1));
}
cout << b.c_str() << endl;
return 0;
}
参考:
点此
方法二:reverse()
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
string a, b;
getline(cin, a);
reverse(a.begin(),a.end());
cout << a;
return 0;
}
参考:
点此
5. 字符串的输入输出处理
#include<iostream>
#include<cstdio>
#include<string.h>
using namespace std;
char a[1000];
int main()
{
int n;
string ss;
cin>>n;
getchar();
for(int i=0;i<n;i++)
{
gets(a);
puts(a);
cout<<endl;
}
while(cin>>ss)
{
cout<<ss<<endl << endl;
}
return 0;
}
6. 3n+1 Problem
7. 蛇形矩阵
#include <iostream>
using namespace std;
int main()
{
int n , count , c = 1 , b = 1;
cin >> n;
int a[n+1][n+1];
for(int i = 1 ; i <= n ; i++)
{
count = i+1;
a[i][1] = c;
c += b;
b++;
for(int j = 2 ; j <= n ; j++)
{
a[i][j] = a[i][j-1]+count;
count++;
}
}
for(int i = 1 ; i <= n ; i++)
{
for(int j = 1 ; j <= n-i+1 ; j++)
{
cout << a[i][j] << " ";
}
cout << endl;
}
}
8. DNA
#include <iostream>
using namespace std;
int main()
{
int n , m , sum;
cin >> m ;
while(m--)
{
cin >> n >> sum;
int a[n+1][n+1];
//int m = (n+1)/2;
for(int i = 1 ; i <= n ; i++)
{
for(int j = 1 ; j <= n ; j++)
{
a[i][j] = 0;
if(i == j)
{
a[i][j] = 1;
}
a[i][n-i+1] = 1;
}
}
while(sum--)
{
for(int i = 1 ; i <= n-1 ; i++)
{
for(int j = 1 ; j <= n ; j++)
{
if(a[i][j] == 1)
{
cout << "X";
}
else
{
cout << " ";
}
}
cout << endl;
}
}
for(int i=n;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
if(a[i][j] == 1)
{
cout << "X";
}
else
{
cout << " ";
}
}
}
cout << endl << endl;
}
}
9. K-进制数
#include<iostream>
using namespace std;
int main()
{
int n, k,res_0 = 1,res_1;
cin >> n >> k;
res_1 = k - 1;
for (int i = 1; i < n; i++)
{
int last_res_1 = res_1;
res_1 = (k - 1) * (res_1 + res_0);
res_0 = last_res_1;
}
cout << res_1;
}
10. Tom数
#include<iostream>
using namespace std;
int main()
{
long n , sum = 0;
while (scanf("%ld",&n))
{
sum = 0;
while (n)
{
sum += n % 10;
n /= 10;
}
cout << sum << endl;
}
}