1. 输出类型
- 不知道输出个数
while(scanf("%d",&a)!=EOF){具体实现逻辑}
while(cin >> a){具体实现逻辑}
- 读取字符串的方法
2. 注意事项
- 数据超出范围的解决方法
- long long %lld 增加数据长度
- 改变算法!!!
#include <iostream>
using namespace std;
int main()
{
//
long long n;
cin >> n;
cout << n * (n + 1) / 2;
return 0;
}
- 简单数学对代码的优化
例题一
#include <iostream>
using namespace std;
//LCM(A,B)=a*b/GCD(a,b)
int GCD(int a,int b) {
if (b == 0)return a;
else
{
int temp =a%b;
a = b;
b = temp;
GCD(a, b);
}
}
int main()
{
int a, b;
cin >> a >> b;
cout << a * b / GCD(a, b);
}
例题二、寻找循环节
#include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a;
b = a % 10;
if (a == 2)
{
int arr[] = { 2, 4, 8, 6 };
cout << arr[a%4-1];
}
else if(a==3)
{
int arr[] = { 3, 9, 7, 1 };
cout << arr[a % 4 - 1];
}
else if (a == 4)
{
int arr[] = { 4, 6 };
cout << arr[a % 2 - 1];
}
else if (a == 7)
{
int arr[] = { 7, 9, 3, 1 };
cout << arr[a % 4 - 1];
}
else if (a == 8)
{
int arr[] = { 8, 4, 2, 6 };
cout << arr[a % 4 - 1];
}
else if (a == 9)
{
int arr[] = { 9, 1 };
cout << arr[a % 2 - 1];
}
else
{
cout << a;
}
return 0;
}
例题三、
#include <iostream>
using namespace std;
int main()
{
// 7 11 18 29 47 76 123 199
// 1 2 0 2 2 1 0 1
int a;
cin >> a;
if (a % 8==3 or a%8==7) {
cout << "yes";
}
else
{
cout << "no";
}
return 0;
}
例四、快速幂
#include <iostream>
using namespace std;
int fastPower(int base, int exponent) {
int result = 1;
for (int i = 0; i <= exponent; i++)
{
if (exponent % 2 == 1) {
result *= base;
}
base = base* base;
exponent = exponent / 2;
}
return result;
}
int main()
{
int a, b;
cin >> a >> b;
cout << fastPower(a, b) << endl;
return 0;
}