Tuesday, March 26, 2013

HOW MANY GAMES (SPOJ)

EXPLAINATION//


Write the average score x as a reduced fraction x=p/q. This means that p and q are integers, that q is positive and that q is minimal (or, equivalently, that p and q have no nontrivial common factor). Then the player can have played any multiple of q games hence the minimum number of games the player should have played is q.

When x=−30.25, note that −30.25=−1214 and −121 and 4 have no common factors except +1 and −1, hence the minimum number of games is indeed 4.

basically we have to convert the avg into fraction part p/q then calculate the gcd(p,q) 
answer will be q/gcd(p,q)



SOLUTION//


#include<stdio.h>
int gcd(int a,int b)
{
    if(b==0)
        return a;
    else
        gcd(b,a%b);
}
int main()
{
int t,num,count,i,j,len,pow,flag;
char s[50];
scanf("%d",&t);
while(t--)
{
scanf("%s",s);
len=strlen(s);
count=0,flag=1;
for(j=len-1;j>=0;j--)
{
if(s[j]=='.'){
flag=0;
break;
}
else
count++;
}
num=0;
for(j=0;j<len;j++)
{
if(s[j]!='.')
num=10*num+(s[j]-'0');
}
pow=1;
if(flag==0){
for(i=0;i<count;i++)
{
pow=pow*10;
}
}
printf("%d\n",pow/gcd(num,pow));
}
return 0;
}



2 comments:

  1. hey why u have minus 0 from s[j]ie.. num=10*num+(s[j]-'0'); please explain

    ReplyDelete
  2. #include
    using namespace std;
    int main() {
    int t,int_part,num;
    double n,dec_part;
    cin>>t;
    while(t--) {
    cin>>n;
    num=1;
    int_part=int(n*10000)/10000;
    dec_part=(n-int_part);
    if(dec_part!=0) {
    while(1) {
    float temp=dec_part*num;
    int int_part_temp=int(temp*10000)/10000;
    double dec_part_temp=(temp-int_part_temp);
    if(dec_part_temp==0)
    break;
    else
    num++;
    }
    }
    cout<<num<<endl;
    }
    }

    What is wrong with this code? It is multiplying the decimal part till an integer is obtained, but spoj still says wrong answer

    ReplyDelete