#import "Fraction.h"
@implementation Fraction
@synthesize numerator, denominator;
-(void) print
{
int whole, num2;
BOOL needToReduce;
if ( numerator >= denominator)
needToReduce = YES;
if (needToReduce == YES)
{
whole = numerator / denominator;
num2 = numerator % denominator;
if (numerator % denominator == 0)
NSLog(@" %i ", whole);
else
NSLog(@" %i %i/%i ", whole, num2, denominator);
}
else
NSLog(@" %i/%i ",numerator, denominator);
}
-(double) convertToNum
{
if ( denominator != 0 )
return (double) numerator / denominator;
else
return 1;
}
-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}
-(id) add: (id) f
{ //add fractions together
// result stores the reult of the addition
Fraction *result = [[Fraction alloc] init];
double resultNum, resultDenom , fnum ;
if ( f < 0)
{
fnum = -1 * [f numerator];
resultNum = numerator * [f denominator ] - denominator * fnum ;
resultDenom = denominator * [f denominator];
[result setTo:resultNum over: resultDenom];
}
else
{
resultNum = numerator * [f denominator ] + (denominator * [ f numerator ]);
resultDenom = denominator * [ f denominator ];
[result setTo:resultNum over: resultDenom];
}
if (resultNum > resultDenom)
{
[result reduce];
}
return result;
}
-(Fraction *) subtract: (Fraction *) f
{
//subtract fractions
Fraction *result = [[Fraction alloc] init];
int resultNum1, resultNum2, resultDenom, resultNum;
if ( f < 0)
{
f.numerator = -1 * f.numerator;
resultNum1 =(numerator * f.denominator) ;
resultNum2 = (denominator * f.numerator);
resultDenom = (denominator * f.denominator);
resultNum = resultNum1 + resultNum2;
[result setTo:resultNum over: resultDenom];
}
else {
resultNum1 =(numerator * f.denominator) ;
resultNum2 = (denominator * f.numerator);
resultDenom = (denominator * f.denominator);
resultNum = resultNum1 - resultNum2;
[result setTo:resultNum over: resultDenom];
}
if (resultNum > resultDenom)
{
[result reduce];
}
return result;
}
-(Fraction *) multiply: (Fraction *) f
{
Fraction *result = [[Fraction alloc]init];
int resultNum, resultDenom;
if ( f < 0)
{
f.numerator = -1 * f.numerator;
resultNum = numerator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo:resultNum over: resultDenom];
}
else
{
resultNum = numerator * f.numerator;
resultDenom = denominator * f.denominator;
[result setTo:resultNum over: resultDenom];
}
if (resultNum > resultDenom)
{
result.reduce;
}
return result;
}
-(Fraction *) divide: (Fraction *)f
{
Fraction *result = [[Fraction alloc]init];
int resultNum, resultDenom;
resultNum = numerator * f.denominator;
resultDenom = denominator * f.numerator;
[result setTo:resultNum over: resultDenom];
if (resultNum > resultDenom)
{
result.reduce;
}
return result;
}
-(void) reduce
{
int u = numerator;
int v = denominator;
int temp;
while ( v != 0)
{
temp = u % v;
u = v;
v = temp;
}
numerator /= u;
denominator /= u;
}
@end