Pages

Saturday, December 26, 2009

Objective-C. 0 + 1/2 + 1/4 + 1/8 + 1/16 +...




Google knows too much. Actually, I was surprised to find out that I can check my math exercise without a calculator or another application. I have to learn Objective-C and now I do not see another way but make simple math exercises.

Here is a program calculating the same formula - sum of fractions 1/2, 1/4, 1/8, etc. The denominator is always 2 in power of n. If the n is big enough the result, the sum of this series should approach 1.

#import <Foundation/Foundation.h>
#import "Fraction.h"

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

Fraction *fraction = [[Fraction alloc] init];
Fraction *sum = [[Fraction alloc] init];
int n, i, pow2;

[sum setTo: 0 over: 1];

NSLog(@"Enter your value for n:");
scanf("%i", &n);

pow2 = 2;
for (i = 1; i <= n; ++i)
{
[fraction setTo: 1 over: pow2];
[sum add: fraction];
pow2 *= 2;
}

NSLog(@"After %i iteration, the sum is %g", n, [sum convertToNum]);

[fraction release];
[sum release];
[pool drain];
return 0;
}

And here is the console:


This program uses the class Fraction declared in file Fraction.h:

#import <Foundation/Foundation.h>


@interface Fraction : NSObject {
int numerator;
int denominator;
}

@property int numerator, denominator;

-(void) print;
-(double) convertToNum;
-(void) setTo: (int)n over: (int)d;
-(void) add: (Fraction*) fraction;
-(void) reduce;

@end

and the class is implemented in Fraction.m:

#import "Fraction.h"

@implementation Fraction

@synthesize numerator, denominator;

-(void)print
{
NSLog(@"%i/%i", numerator, denominator);
}

-(double)convertToNum
{
if (denominator != 0)
return (double) numerator / denominator;
return 1.0;
}

-(void) setTo: (int) n over: (int) d
{
numerator = n;
denominator = d;
}

-(void)add: (Fraction*) fraction
{
numerator = numerator * fraction.denominator + fraction.numerator * denominator;
denominator = denominator * fraction.denominator;
[self reduce];
}

-(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

No comments:

Post a Comment