简体   繁体   English

在该变量上执行操作时,有哪些方法可以在C ++中用更少的编译时间在变量中存储很大的整数值?

[英]What are various methods to store very large integer value in a variable with less compilation time in C++ when doing operation on that variable

我应该如何处理此变量以使其在不下载任何新库的情况下存储大量变量。我正在谈论使用某种操作(例如哈希或数组)或我不知道的东西。

If you don't need to perform any operations on that variable and can't use any libraries, including the C++ standard library, then use 如果您不需要对该变量执行任何操作并且不能使用任何库,包括C ++标准库,请使用

const char* x = "1119191991900234245239919234772376189636415308431";

else the next best thing to use is a 否则,下一个最好的东西是

std::string x = "1119191991900234245239919234772376189636415308431";

Even elementary arithmetic can be performed on such an encoding, the digit value at position n in the string is x[n] - '0' . 甚至可以对这种编码执行基本算术,字符串中位置n的数字值为x[n] - '0'


But all this is really rather silly. 但这一切确实很愚蠢。 Suggest you look at the big number library that's part of the Boost distribution. 建议您查看Boost发行版中的大数字库。 See www.boost.org. 见www.boost.org。

For fun I've written something that works only on strings. 为了好玩,我写了一些只适用于字符串的东西。 By the way, that number you gave is awfully large number, it's something like a quintillion times the mass of our solar system in kg. 顺便说一句,您给的数字非常大,大约是我们的太阳系质量(以千克为单位)的五百亿倍。

There are two methods. 有两种方法。 The first one adds one to the number and checks if it's a palindrome. 第一个将数字加一个,然后检查它是否是回文。 This is a slow version, but can still works for numbers up to like about 16 digits in a reasonable time. 这是一个较慢的版本,但仍可以在合理的时间内处理大约16位数字。

The second method is the method better way, it basically copies the left side of the number to the right side, it's pretty much instant. 第二种方法是更好的方法,它基本上将数字的左侧复制到右侧,这几乎是即时的。 As the code is now you can run it through both to cross-reference the results. 由于现在是代码,因此您可以同时运行它们以交叉引用结果。

I can't say it's fool-proof and I'm sure there's errors in it, but it seems to work, and I did have fun writing it. 我不能说它是万无一失的,并且我肯定其中有错误,但是它似乎可行,并且编写它确实很有趣。 Also, if you're not allowed to use ANY libraries whatsoever, it's rather easy to refactor, just use raw strings and pass the size in the function. 另外,如果不允许使用任何库,则重构非常容易,只需使用原始字符串并在函数中传递大小即可。

#include <iostream>
#include <string>
#include <chrono>
#include <stdexcept>
#include <cstring>

using namespace std::chrono;
using namespace std;

auto startT = high_resolution_clock::now();
auto endT = high_resolution_clock::now();
double timeTaken;

#define STARTCLOCK startT = high_resolution_clock::now();
#define STOPCLOCK endT = high_resolution_clock::now();
#define PRINT_ELAPSED_TIME timeTaken = duration_cast<milliseconds>(endT - startT).count() / 1000.0; \
                            cout << "Process took " << timeTaken << " seconds\n\n";


void addOneTo(std::string& value)
{
    int64_t idx = value.size();

    do 
    {
        --idx;
        if (idx < 0) {
            memset(&value[0], '0', value.size());
            value.insert(value.begin(), '1');
            return;
        }
        value[idx] += char(1);
        if (value[idx] > '9') { value[idx] = '0'; }

    } while (value[idx] == '0');
}

bool isPalindrome(const std::string& number)
{
    const char* start = &number[0];
    const char* end = &number[number.size() - 1];

    while (start <= end)
    {
        if (*start != *end) return false;
        ++start;
        --end;
    }
    return true;
}

std::string getSmallestPalindromeByBruteForceBiggerThan(std::string num)
{
    if (num.empty()) throw std::runtime_error("Empty string");

    while (true)
    {
        addOneTo(num);
        if (isPalindrome(num)) return num;
    }
}


std::string getSmallestPalindromeOptimisedWayBiggerThan(std::string num)
{
    if (num.empty()) throw std::runtime_error("Empty string");

    addOneTo(num);
    if (num.size() == 1) return num;
    int64_t left;
    int64_t right;

    left = num.size() / 2 - 1;

    if (num.size() % 2 == 0)  right = num.size() / 2; 
    else right = num.size() / 2 + 1;

    if (num[left] < num[right])
    {
        ++num[left];
        num[right] = num[left];
    }

    for (; left >= 0 && right < num.size(); --left, ++right)
    {
        num[right] = num[left];
    }

    return num;
}

int main()
{
    string number = "60819750046451377";

    STARTCLOCK
    string palindrome = getSmallestPalindromeByBruteForceBiggerThan(number);

    cout << "____BRUTE FORCE____\n";
    cout << "Smallest palindrome = \n" << palindrome << '\n';

    STOPCLOCK
    PRINT_ELAPSED_TIME

    STARTCLOCK

    palindrome = getSmallestPalindromeOptimisedWayBiggerThan(number);

    cout << "____OPTIMISED____\n";
    cout << "Smallest palindrome = \n" << palindrome << '\n';

    STOPCLOCK
    PRINT_ELAPSED_TIME

    cin.ignore();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM