JKBigInteger icon indicating copy to clipboard operation
JKBigInteger copied to clipboard

SquareRoot unavailable.

Open Apps4LifeLLC opened this issue 8 years ago • 0 comments

There is no square-root method which would be very useful. I've taken the liberty of writing a square-root approximation code that will get about 99.9% accurate to the actual value. Having a "SquareRootApprox" function would even be useful to many programmers I'd assume. (*Note: uses containsString which is iOS8+, this can be converted to .rangeOfString != for further compatability.

`

-(NSString *)squareRootEstimateOfNumber:(NSString *)number {

if ([number containsString:@"."]) {
    number = [[number componentsSeparatedByString:@"."] objectAtIndex:0];
}

int significantDigits = (int)[pString @"%i", INT_MAX].length-1;
significantDigits-=significantDigits%2;

JKBigDecimal *numberJKF = [[JKBigDecimal alloc] initWithString:number];
int numberOfDigits = (int)number.length;

if (numberOfDigits <= significantDigits) {
    return [pString @"%i", (int)round(sqrt([number floatValue]))];
} else {
    JKBigDecimal *tenJKF = [[JKBigDecimal alloc] initWithString:@"10"];
    int divisorExponent = numberOfDigits-significantDigits-(numberOfDigits%2);
    int factorExponent = (int)((float)divisorExponent/2.0f);
    JKBigDecimal *divisorJKF = [[JKBigDecimal alloc] initWithString:@"1"];
    divisorJKF = [tenJKF pow:divisorExponent];
    JKBigDecimal *factorJKF = [[JKBigDecimal alloc] initWithString:@"1"];
    factorJKF = [tenJKF pow:factorExponent];

    float significantFigures = (float)[[[numberJKF divide:divisorJKF] stringValue] floatValue];
    int significantRoot = (int)round(sqrt(significantFigures));
    JKBigDecimal *significantRootJKF = [[JKBigDecimal alloc] initWithString:[pString @"%i", significantRoot]];

    JKBigDecimal *estimateRootJKF = [[JKBigDecimal alloc] initWithString:@"1"];
    estimateRootJKF = [significantRootJKF multiply:factorJKF];

    return [estimateRootJKF stringValue];
}

}

`

Apps4LifeLLC avatar Jul 06 '16 00:07 Apps4LifeLLC