Tuesday, December 24, 2013

codechef GCD2 - "gcd2" guidance and solution

codechef GCD2 - "gcd2": http://www.codechef.com/problems/GCD2

codechef GCD2 - "gcd2" solution: http://ideone.com/sNmT36

#include <iostream>
#include <cstring>
using namespace std;

char arr[255];

int mod(int a) {
int c=0;
for(int i=0; i<strlen(arr); i++) c=((arr[i]-'0')+c*10)%a;
return c;
}

int gcd(int a, int b) {
if(b==0) return a;
else return gcd(b, a%b);
}

int main() {
// your code goes here
int n, a;
cin>>n;
while(n--) {
cin>>a>>arr;
if(a==0) cout<<arr<<endl;
else {
int d=mod(a);
cout<<gcd(a, d)<<endl;
}
}
return 0;
}

codechef GCD2 - "gcd2" guidance: 

look for ASCII codes - http://en.wikipedia.org/wiki/ASCII, there '0' starts with 48. so when getting character arr[i] just arr[i]-'0' or arr[i]-48 to get 0 as a result.
and pay attention to mod, hope this helps: http://discuss.codechef.com/questions/2475/gcd2-problem-easy

here is my draft to get "B" as a string array, on my draft i used ".size()" to get size; however, on the above code i used "strlen": http://ideone.com/E6dp20
#include <iostream>
#include <cstring>
using namespace std;

int main() {
// your code goes here
int b=0, c;
string a;
cin>>a>>c;
for(int i=0; i<a.size(); i++) {b=b*10+a[i]-48; if(b>c) b=b%c;}
cout<<b<<endl<<a.size();
return 0;
}

No comments:

Post a Comment