Posted: Tue Jun 10, 2003 10:28 pm
I think you should use bit-wise operations instead of time-consuming multiplication. For example, instead of
[cpp]
a = a*256;
[/cpp]
you should use
[cpp]
a = a<<8;
[/cpp]
and instead of
[cpp]
a = a*256*256;
[/cpp]
you should use
[cpp]
a = a<<16;
[/cpp]
that should speed up your code.
this is how your code should look like
[cpp]
#include<iostream>
#include<string>
using namespace std;
string output(int a){
string result,no="0123456789ABCDEF";
for(int j=1;j<=4;a>>=4,j++){
int i=a%16;
result=no+result;
}
return result.substr(0,2)+" "+result.substr(2);
}
int main(){
string buffer;
int i;
while(true){
string buffer;
char bu;
while(cin.get(bu)){
if(bu=='\n')
break;
buffer=buffer+bu;
}
if(buffer[0]=='#')
return 0;
int length=buffer.length(),base=0,checksum;
if(length==0){
cout<<"00 00"<<endl;
continue;
}
for(i=0;i<length;i++)
base=(base<<8+buffer)%34943;
base=(base<<16)%34943;
checksum= (base==0?base:(34943-base));
cout<<output(checksum)<<endl;
}
return 0;
}[/cpp]
[cpp]
a = a*256;
[/cpp]
you should use
[cpp]
a = a<<8;
[/cpp]
and instead of
[cpp]
a = a*256*256;
[/cpp]
you should use
[cpp]
a = a<<16;
[/cpp]
that should speed up your code.
this is how your code should look like
[cpp]
#include<iostream>
#include<string>
using namespace std;
string output(int a){
string result,no="0123456789ABCDEF";
for(int j=1;j<=4;a>>=4,j++){
int i=a%16;
result=no+result;
}
return result.substr(0,2)+" "+result.substr(2);
}
int main(){
string buffer;
int i;
while(true){
string buffer;
char bu;
while(cin.get(bu)){
if(bu=='\n')
break;
buffer=buffer+bu;
}
if(buffer[0]=='#')
return 0;
int length=buffer.length(),base=0,checksum;
if(length==0){
cout<<"00 00"<<endl;
continue;
}
for(i=0;i<length;i++)
base=(base<<8+buffer)%34943;
base=(base<<16)%34943;
checksum= (base==0?base:(34943-base));
cout<<output(checksum)<<endl;
}
return 0;
}[/cpp]