-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfactor.m
67 lines (59 loc) · 1.63 KB
/
factor.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#import <Foundation/Foundation.h>
@interface Factor : NSObject
- (NSArray*)factorize:(int)num;
@end
@implementation Factor
- (NSArray*)factorize:(int)num
{
// NSMutableArray *arr = [NSMutableArray arrayWithCapacity: 100];
NSMutableArray *arr = [[NSMutableArray alloc] init];
int i = 2;
int resultIdx = 0;
while (i * i < num) {
while (num % i == 0) {
[arr addObject: [NSNumber numberWithInt: i]];
// NSLog(@"%d" @"=" @"%d", i, resultIdx);
resultIdx++;
num /= i;
}
i++;
}
if (num > 1) {
[arr addObject: [NSNumber numberWithInt: num]];
NSLog(@"%d", num);
}
return arr;
}
@end
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSLog(@"Hi, this is about factor algorithm by Objective-C");
// Factor *factor = [[Factor alloc] init];
Factor *factor = [Factor new];
int num = 120;
NSArray *arr = [factor factorize: num];
NSLog(@"%@", arr);
// echo
NSLog(@"%d = ", num);
for (id obj in arr)
{
NSLog(@"%@ *", obj);
}
// echo
printf("%d = ", num);
for (int i = 0; i < [arr count]; i++)
{
if (i != 0) {
printf(" * ");
}
printf("%d", [arr[i] intValue]);
}
}
return 0;
}
/*
jarry@jarrys-MacBook-Pro factor % gcc -lc factor.m -framework Foundation
jarry@jarrys-MacBook-Pro factor % g++ -lc factor.m -framework Foundation
jarry@jarrys-MacBook-Pro factor % cc -lc factor.m -framework Foundation
jarry@jarrys-MacBook-Pro factor % ./a.out
*/