33,008
社区成员
发帖
与我相关
我的任务
分享
//复杂度大概为GCD(s1*n1,s2*n2)
#include <iostream>
#include <vector>
using namespace std;
int gcd(int a,int b){
if(a<b)
return gcd(b,a);
if(!(a%b))
return b;
else
return gcd(b,a%b);
}
int max(int a,int b){
return (a>b?a:b);
}
int main(){
int basic1(1000),step1(5),number1(15);
int basic2(1000),step2(15),number2(13);
int max_divisor=gcd(step1*number1,step2*number2);
int b,s,n;
int bt,st,nt;
vector<int> v_sum(0);
if(basic1>basic2){
b = basic1;
s = step1;
n = number1;
bt = basic2;
st = step2;
nt = number2;
}
else{
b = basic2;
s = step2;
n = number2;
bt = basic1;
st = step1;
nt = number2;
}
for(int sum = b;sum < b+s*n && sum < bt+max_divisor;sum += s){
if(!((sum-bt)%st) || !((sum-bt)%nt)){
v_sum.push_back(sum);
cout<<sum<<endl;
}
}
int first,end;
first = max(basic1,basic2);
end = max(basic1+step1*number1,basic2+step2*number2);
if(end<first)
cout<<"数量:"<<0<<endl;
else{
int x = 0;
for(vector<int>::iterator pfirst = v_sum.begin();(*pfirst <= (end-first)% max_divisor) && pfirst != v_sum.end();++pfirst){
++ x;
}
cout<<"数量:"<<x+v_sum.size()*((end-first)/max_divisor);
}
system("pause");
return 0;
}
#define UINT unsigned int
#define METHOD(base, num, step) (base + (num - 1)*step)
#define SAME_PART_NUM(max, base, step) ((max - base)/step)
bool SameNum(UINT base1, UINT num1, UINT step1,
UINT base2, UINT num2, UINT step2)
{
UINT base2_same_part_num_max = 0;
UINT i = 0;
/* have same number part */
if ((base1 <= base2)
&& (METHOD(base1, num1, step1) >= base2))
{
/* (b2 + x*s2) == (b1 + y*s1) */
/* so, y = (b2 - b1 + x*s2)/s1 */
/* so, we use (0 == (b2 - b1 + x*s2)%s1) */
base2_same_part_num_max = SAME_PART_NUM(METHOD(base1, num1, step1) - base2)/step2;
for (i = 0; i <= base2_same_part_num_max, i++)
{
if (0 == (base2 - base1 + i*step2)%step1)
{
return true;
}
}
return false;
}
else
{
SameNum(base2, num2, step2, base1, num1, step1);
}
}
// input (basic1, number1, step1), (basic2, number2, step2)
// find the start and the end that we need to compare, in this case we have the least times of loop, not difficult to do so
int b = basic1 - basic2;
for(int i=start;i<ends;i++)
{
if( (step1*i + b) % step2 )
return false; // which means there is a dulplicate
else
continue; // no duplicate
}
return true;