簡體   English   中英

我如何使我的代碼與眾不同以刪除時間限制?

[英]How can i make my code different to remove the time limit?

問題是:有一張帶8位數字的彩票。 第一張票號為M,最后一張票號為N。 大小M和N滿足以下關系:10000000≤M <N≤99999999。您需要確定給定數字之間的“幸運”彩票數目。 如果前四位數之和等於后四位數之和,則票證被視為“幸運”。 這是我的代碼:

#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int calcSumDigits(int n)
{
    int sum=0;
    while (n!=0)
    {
        sum+=n%10;
        n/=10;
    }
    return sum;
}
int main(void)
{
    int a,b,cnt=0,x,y;
    cin>>a>>b;
    for (int i=a;i<=b;i++)
    {
        x=i%10000;
        y=(i-x)/10000;
        if (calcSumDigits(x)==calcSumDigits(y)) cnt++;
    }
    cout<<cnt;
    return 0;
}

結果是正確的,但是程序要花點時間才能得出結果。 例如,當我嘗試從10000000到99999999時,結果顯示4379055,但需要6秒鍾以上

您只需要比較由數字的每半部分的所有排列生成的兩組總和-為簡化起見,我對數字進行了四舍五入:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;
int calcSumDigits(int n)
{
    int sum=0;
    while (n!=0)
    {
        sum+=n%10;
        n/=10;
    }
    return sum;
}
int SlowVersion(int a, int b) {
    int cnt=0,x,y;
    for (int i=a;i<=b;i++)
    {
        x=i%10000;
        y=(i-x)/10000;
        if (calcSumDigits(x)==calcSumDigits(y)) cnt++;
    }
    return cnt;
}
int main()
{
    int lower;
    int upper;
    int original_lower;
    int original_upper;
    cout<<"enter lower:";
    cin>>original_lower;
    cout<<"enter upper:";
    cin>>original_upper;

    lower = original_lower - (original_lower%10000);
    upper = original_upper + (9999 - (original_upper%10000));

    cout<<"to simplify the calculations the lower was changed to:" << lower << endl;
    cout<<"to simplify the calculations the upper was changed to:" << upper << endl;

    int cnt=0;
    const int b=lower%10000;
    const int a=(lower-b)/10000;
    const int b_top=upper%10000;
    const int a_top=(upper-b_top)/10000;
    int a_sums[a_top-a];
    int b_sums[b_top-b];


    int counter = 0;
    for (int i=a;i<=a_top;i++)
    {
        a_sums[counter] = calcSumDigits(i);
        counter++;
    }
    counter = 0;
    for (int x=b;x<=b_top;x++)
    {
        b_sums[counter] = calcSumDigits(x);
        counter++;
    }

    int countera = 0;
    int counterb = 0;
    for (int i=a;i<=a_top;i++)
    {
        counterb = 0;
        for (int x=b;x<=b_top;x++)
        {
            if (a_sums[countera]==b_sums[counterb]) cnt++;
            counterb++;
        }
        countera++;
    }

    cnt = cnt - SlowVersion(lower,original_lower-1);
    cnt = cnt - SlowVersion(original_upper+1,upper);

    cout << "The total \"lucky numbers\" are " << cnt << endl;

    cout << "a is " << a << endl;
    cout << "b is " << b << endl;
    cout << "a_top is " << a_top << endl;
    cout << "b_top is " << b_top << endl;
    system("PAUSE");
    return 0;
}

輸入的結果為4379055(得到的結果相同),運行速度非常快。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM