tl; dr20! * 20!
: Objective-Cのように数字をどのように扱うべきですか?
私はProjectEulerを通じてObjective-Cを学んでいます。とても楽しかったですが、私が遭遇した問題の1つは、任意の数を処理することです。私はまだこれらのことについてかなり環境に配慮しているので、たとえばPythonのようなものがObj-Cと比較して簡単に多数を処理する理由がわかりません。
たとえばProblem 15
:
Starting in the top left corner of a 2 x 2 grid, there are 6 routes (without backtracking) to the bottom right corner.
How many routes are there through a 20 x 20 grid?
簡単だ。組み合わせ論の使用:
(20 + 20)!/ 20!(20!)
-> 815915283247897734345611269596115894272000000000 / 5919012181389927685417441689600000000-
> 137846528820
Pythonの場合:
import math
print math.factorial(40) / (math.factorial(20) * math.factorial(20))
しかし、Objective-Cでは?私はまだそのような多数を強制的に通過させる方法を見つけていません。2x2の例を使用すると問題なく動作します。9C4 = 126
あるべき姿で手に入れることができます。しかし、私はどのように次のような数字を扱うべき20!
ですか?
に変換でき、精度が低下してもかまわないとNSDecimalNumber
仮定して、数値ごとにより多くの数字をサポートしているように見えるを使用しようと試みましたが、理解できなかったため、あまり有用ではありませんでした。 Mantissa x Exponent
Obj-Cにaから仮数を作成させる方法を説明します。精度が低下し%llu
てもかまいません。
私がこれまでに持っているコードは、unsigned long long
非常に大きな値を処理しているように見えるので、階乗を適切に生成しますが、で窒息しx * y
、したがってをgetCombinatoricOf:20 and:20
返します1
。
#import "Problem15.h"
@implementation Problem15
- (unsigned long long)factorial:(NSNumber *)number {
unsigned long long temp = 1;
for (int i = [number intValue]; i > 0; i--) {
temp *= i;
}
return temp;
}
- (unsigned long long)getCombinatorcOf:(NSNumber *)x and:(NSNumber *)y {
NSNumber *n = @([x intValue] + [y intValue]);
NSNumber *n_factorial = @([self factorial:n]);
NSNumber *x_factorial = @([self factorial:x]);
NSNumber *y_factorial = @([self factorial:y]);
return ([n_factorial unsignedLongLongValue] / ([x_factorial unsignedLongLongValue] * [y_factorial unsignedLongLongValue]));
}
- (NSString *)answer {
NSNumber *x = @5;
NSNumber *y = @4;
unsigned long long answer = [self getCombinatoricOf:x and:y];
return [NSString stringWithFormat:@"\n\nProblem 15: \nHow many routes are there through a 20 x 20 grid? \n%llu", answer];
}
@end