← Back to topics
Topic

z-easy

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

m
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
A
Al3kSaNdaR
You need to speed up your NZD ( GCD ) function, try searching for Euklid's recursive algorithm on google.
D
Diabolic
Thanks for the posts but its still not working. Yes I use the Euclid algorithm.
b
boris4
well, you are using

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

but you can use

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

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

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


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

Thanks in advance.
b
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 );
}
D
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:


b
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.
D
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
b
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 )
D
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.
b
boris4
change:

long long nzd( long a, long b )

to:

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