Skip to content

Instantly share code, notes, and snippets.

@bitdewy
Last active December 15, 2015 21:29
Show Gist options
  • Save bitdewy/5325991 to your computer and use it in GitHub Desktop.
Save bitdewy/5325991 to your computer and use it in GitHub Desktop.
Project Euler #1 in Object-C
//
// 1.m
// ProjectEuler
//
// Created by bitdewy on 4/6/13.
// Copyright (c) 2013 bitdewy. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface SumOfValuesMultiples : NSObject {
int _max;
NSMutableArray* _values;
}
- (void) setMax: (int) max;
- (void) addValue: (int) v;
- (int) calc;
- (bool) match: (int) v;
@end
@implementation SumOfValuesMultiples
- (id)init {
self = [super init];
if (self) {
_values = [[NSMutableArray alloc] init];
}
return self;
}
- (void) setMax: (int) max {
_max = max;
}
- (void) addValue: (int) v {
if (v != 0) {
[_values addObject: [NSNumber numberWithInt: v]];
}
}
- (int) calc {
int sum = 0;
for (int i = 0; i < _max; ++i) {
if ([self match: i]) {
sum += i;
}
}
return sum;
}
- (bool) match: (int) v {
for (int i = 0; i < [_values count]; ++i) {
if (v % [[_values objectAtIndex: i] intValue] == 0) {
return true;
}
}
return false;
}
@end
int main(int argc, const char * argv[])
{
@autoreleasepool {
SumOfValuesMultiples* o = [[SumOfValuesMultiples alloc] init];
[o setMax: 1000];
[o addValue: 3];
[o addValue: 5];
NSLog(@"%d", [o calc]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment