问题是: 有一张8位数的门票。第一张票有M号,最后一张 - N号。幅度M和N满足以下关系:10000000≤M<1。 N≤999999999。您需要确定&#34;幸运&#34;给定数字之间的票。门票被认为是#34;幸运&#34;如果前四位的总和等于后四位的总和。 这是我的代码:
#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;
}
结果是正确的但是从程序中得到结果需要花费一点时间。对于ex,当我尝试从10000000到99999999时,结果显示4379055,但需要超过6秒
答案 0 :(得分:0)
你只需要比较你的数字的每一半的所有排列所产生的两组总和 - 简化我将数字四舍五入:
#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(获得相同的结果)并且运行速度更快。