微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

排序字符串中提供的大数字列表而不计算它们的值

如何解决排序字符串中提供的大数字列表而不计算它们的值

一个给定的数字列表,它们以字符串格式 x^y 或 z! 编写。例如 1000^1000、954! 525^419,89!,427!,428^727... x,y,z 是区间 内的随机值。该列表最多可包含 200 个这些公式。我需要根据这些公式的值按升序对这个给定的字符串列表进行排序,而不计算这些值。如何在不计算其值的情况下检查某个阶乘是否大于某个幂数?

解决方法

来自comment

我需要以某种方式进行检查,没有这些值会更好,因为程序有一定的时间限制才能完成。

要排序,您确实需要某种值。由于性能是问题,您可能需要计算近似值

例如计算值的对数

  • 对于“权力”,这很简单:log(x^y) = y * log(x)

  • 对于“阶乘”,您可以使用 log(x!) = Ramanujan's approximation to factorial

    或者,如suggested by risingStark

    不需要近似值。使用 log(x!) = log(x)+log(x-1) + ... + log(1)。由于 x 最多为 1000,因此预先计算累积总和直到 log(1000)

,

这是上述问题的 C++ 代码。

#include <bits/stdc++.h>
using namespace std;

int main(){
    int i,n;
    vector<string> arr = {"1000^1000","954!","525^419","89!","427!","428^727"};
    n = (int)arr.size();
    vector<pair<double,int> > ans;
    vector<double> calc(1001);

    // Since the maximum number is 1000,Pre-calculating the cumulative log sum
    for(i=2;i<=1000;i++){
        calc[i] = log10(i) + calc[i-1];
    }

    for(i=0;i<n;i++){
        string temp = arr[i];
        int x = (int)temp.size();
        if(temp[x-1]=='!'){
            int k = stoi(temp.substr(0,x-1));
            ans.push_back({calc[k],i});
        }else{
            int f = temp.find('^');
            int a = stoi(temp.substr(0,f));
            int b = stoi(temp.substr(f+1));
            ans.push_back({b*log10(a),i});
        }
    }
    sort(ans.begin(),ans.end());
    for(i=0;i<n;i++){
        cout<<arr[ans[i].second]<<" ";
    }cout<<endl;
    return 0;
}

void solve(){
    int i,Pre-calculating the cumulative log sum
    for(i=2;i<=1000;i++){
        calc[i] = log10(i) + calc[i-1];
    }
    for(i=0;i<n;i++){
        string temp = arr[i];
        int x = (int)temp.size();
        if(temp[x-1]=='!'){
            int k = stoi(temp.substr(0,ans.end());
    for(i=0;i<n;i++){
        cout<<arr[ans[i].second]<<" ";
    }cout<<endl;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。