第一题
思路
套路题:一旦对精度有要求,就每次使用增量,每次用增量和精度比较,直到小于精度
代码
注意:
1、精度有正负,但是1e-8必正数,所以比较之前一定取绝对值
2、10^-8表示为 1e-8
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
void function_one(double x) {
double tmp = x;//增量
double ans = 0;
int i = 1;
while (fabs(tmp) >= 1e-8) {
ans += tmp;
tmp *= (double)((-1)*x*x) / (2 * i*(2 * i + 1));
i++;
}
cout << ans;
}
第三题
思路
1、这里不需要判断i是否为质数,因为根据这个算法的特性,在遇到i之前,n中关于i的因数都已经被分解掉了,例如在将6作为因数之前必定已经将这个6分解为了23,在将9作为因数之前必定已经将9分解为了33,因此这里的i一定是个质数
2、从2开始枚举,要么不可除,接着枚举新的因数,要么可一直除下去,直到<1>不可除<2>n==i即最后一项,直接退出去
代码
#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <vector>
#include <algorithm>
using namespace std;
void function_three(int n) {
cout << n << '=';
int i = 2;
for (; i < n; i++) {
while (n != i) {//判断是不是最后一次分解
if (n%i == 0) {
cout << i << '*';
n /= i;
}
else {//推出这层循环,找下一个因子
break;
}
}
}
cout << i;
return;
}
第四题
思路
1、先获得分数,化简并存储一个临时变量里面
2、和答案序列比较,有重复的分数的话本次产生的作废
3、没重复的,插入排序进去
代码
注意:
1、本题算编号时,数据量极大极大,long long 会越界,所以用unsigned long long
2、用这个数据类型时候,切记<1>初始化最下为0 、<2>0-ULLONG_MAX=1,所以二者的值未变化,一定不要用这俩直接减,会出错
#include <string>
#include <stack>
#include <queue>
#include <unordered_map>
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;
struct fraction {//存储分数
int a;
int b;
double val;
};
int GCD(int a, int b) {//获取最大公约数,辗转相除
return b == 0 ? a : GCD(b, a%b);
}
void function_four(int n) {
fraction ans[2000];
int num = 0;
for (int b = 2; b <= n; b++) {//枚举分母
for (int a = 1; a < b; a++) {//枚举分子
//产生真分数,且化简求值
fraction tmp;
int gcd = GCD(a, b);
tmp.a = a / gcd;
tmp.b = b / gcd;
tmp.val = (double)a / b;
bool isSame = false;
//开始插入合适位置,直接插入排序,并且兼顾去重
ans[num++] = tmp;
for (int j = num - 2; j >= 0; j--) {//判断是否含有重复元素
if (tmp.val == ans[j].val) {
num--;//重复元素作废
isSame = true;
}
}
if (!isSame) {//插入排序
for (int j = num - 2; j >= 0; j--) {
if (ans[j + 1].val < ans[j].val) {
fraction help = ans[j + 1];
ans[j + 1] = ans[j];
ans[j] = help;
}
}
}
}
}
for (int i = 0; i < num; i++) {
cout << ans[i].a << '/' << ans[i].b << ' ';
}
return;
}
第六题第二问
详见我的博客:
第八章–排序