有个疑问
查看原帖
有个疑问
1436267
I_Love_Codm楼主2025/2/2 00:08

为什么单精*高精可以:

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void cheng(string &a, int b) {
	string s = to_string(b); int la = a.size(), lb = s.size();
	vector<int> ans(la + lb + 1, 0);
	reverse(a.begin(), a.end());

	for(int i = 0; i < la; i++)
	    ans[i] += (a[i] - '0') * b;
	
	for(int i = 0; i < ans.size() - 1; i++)
	    if(ans[i] > 9) ans[i + 1] += ans[i] / 10, ans[i] %= 10;
	
	reverse(ans.begin(), ans.end());
    while(ans.size() > 1 && !ans[0]) ans.erase(ans.begin());
	a = "";
    for(int val: ans) a += to_string(val);
}

int main() {
	int t;
	cin >> t;
	
	while(t--) {
		int n, cnt = 0; string a;
		cin >> n >> a;

		string result = "1";
		for(int i = 2; i <= n; i++) cheng(result, i);
		//cout << result << ' ';
		int pos = result.find(a);
		while(pos != string::npos && pos < result.size()) {
			pos = result.find(a, pos + 1);
			cnt++;
		}
		
		cout << cnt << '\n';
	}
	
	return 0;
}

高精*高精就不行呢?

#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

string cheng(string a, string b) {
	int la = a.size(), lb = b.size();
	vector<int> ans(la + lb + 1, 0);
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());

	for(int i = 0; i < la; i++)
	    for(int j = 0; j < lb; j++)
	        ans[i + j] += (a[i] - '0') * (b[j] - '0');
	
	for(int i = 0; i < ans.size() - 1; i++)
	    if(ans[i] > 9) ans[i + 1] += ans[i] / 10, ans[i] %= 10;
	
	reverse(ans.begin(), ans.end());
    while(ans.size() > 1 && !ans[0]) ans.erase(ans.begin());
	string result = "";
    for(int val: ans) result += to_string(val);
    return result;
}

string jian(string a) {
	for(int i = a.size() - 1; i >= 0; i--) {
		if(a[i] > '0') {
			a[i]--;
			break;
		}
		a[i] = '9';
	}
	
	while(a.size() > 1 && a[0] == '0') a.erase(a.begin());
	reverse(a.begin(), a.end());
	return a;
}

string factorial(string str) {
	if(str == "1") return "1";
	return cheng(str, factorial(jian(str)));
}

int main() {
	int t, cnt;
	cin >> t;
	
	while(t--) {
		string n, a;
		cnt = 0;
		cin >> n >> a;
		string result = factorial(n);
		int pos = result.find(a);
		while(pos != string::npos && pos < result.size()) {
			pos = result.find(a, pos + 1);
			cnt++;
		}
		
		cout << cnt << '\n';
	}
	return 0;
}
2025/2/2 00:08
加载中...