← Back to topics
Topic

z-easy

Diabolic
Here I got my code for z-easy, but I got either wrong result or time exceeded, whats the problem?
Thanks.

matteo123


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

int nzd(int a,int b)
{
int nzd;
do
{
if (a<b)
b=b-a;
else
a=a-b;
}
while(a!=b);
nzd=a;
return nzd;
}

int main() {
int a,b,c,d,x,y,z;
scanf ("%d/%d%d/%d",&a,&b,&c,&d);
x=a*c;
y=b*d;
z=nzd (x,y);
x=x/z;
y=y/z;
printf ("%d/%d",&x,&y);
}
i think it will work
Al3kSaNdaR
You need to speed up your NZD ( GCD ) function, try searching for Euklid's recursive algorithm on google.
Diabolic
Thanks for the posts but its still not working. Yes I use the Euclid algorithm.
boris4
well, you are using

nzd( a, b ) = nzd( a-b, b )

but you can use

nzd( a, b ) = nzd( a % b, b )
n.vilcins
Just use:
z = __gcd(x, y);

And replace int with long long because numbers can be quite large.
Diabolic
Wait wait, can you exactly point in my original post, where is the error?

Hvala vam puno.
matteo123
you have the Euklid algorithm on wikipedia and there is a code
Diabolic
Lol, now I got all wrong results:


boris4
 int nzd( int a, int b ){ return b == 0 ? a : nzd( a%b, b ); }
Diabolic
boris4 can you please explain the code? Now it doesn't work at all.

Thanks in advance.
boris4
yes, i can :)

to find NZD ( GCD ) for 2 numbers in O( log( max( a, b ) ) ) time you use Euclid's algorithm.

it goes like this

a,b --> read those 2 or something like that
int r = a % b;
while ( r > 0 )
{
a = b;
b = r;
r = a % b;
}
and the result is b.

this one up you get, do with recursion ( it is easier to type and smaller :) )
and it goes

int nzd( int a, int b )
{
if ( b == 0 )
return a;
return nzd( a % b, b );
}
Diabolic
Thank you very much for the efforts.
When I run the program I got:
z-easy.exe stopped working...
windows is checking for solution...
Here is the whole code:


boris4
i'm sorry...

it is


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


I'm sorry again, for this stupid mistake.
Diabolic
Thanks for the code. Why still I Got these Wrong Results for all of the test.
http://www.z-trening.com/new/www/html/submit.php?submit=5000000153
boris4
hmmm... i'm not sure but try:

put << endl at the end of your output
int function you have ( long a, long b ), put
( long long a, long long b )
Diabolic
lol. this is very strange. I tried with 3 algorithms and still could not start working it. I am trying it, and it works, but it doesn't pass the tests. I probably need to contact admin.
boris4
change:

long long nzd( long a, long b )

to:

long long nzd( long long a, long long b )
Diabolic
Now it works. Thank you very much for the help Boris. How many years of experience do u have with programming ?
boris4
hmmm... i think less then 2 years.
I think i started programming in August 2007
tgudlek
Nice work Boris ;)
boris4
thx :)