java - Performance Improvement For Using BigInteger While Calculating Square Root -
i trying calculate square root of integers below 100 precision of 10000 digits. tried using newton's method big decimal, eats lot of time.
so using jarvis method finding square root using biginteger.(i think method involves less number of calculations , gets rid of maintenance of decimal digits). code takes lot of time.the following piece of code depicts calculations.
public class squareroothackerrankjarvis { static biginteger limit; static biginteger a; static biginteger b; private static biginteger squareroot(int n, int digits, biginteger ten, biginteger hundred, biginteger five) { limit = ten.pow(digits + 1); = biginteger.valueof(n * 5); b = biginteger.valueof(5); while (b.compareto(limit) == -1) { if (a.compareto(b) != -1) { = a.subtract(b); b = b.add(ten); } else { = a.multiply(hundred); b = (b.divide(ten)).multiply(hundred).add(five); } } return b.divide(hundred); } public static void main(string[] args) { scanner scanner = new scanner(system.in); int n = scanner.nextint(); int p = scanner.nextint(); int sum = 0; int p = 1; biginteger ten = biginteger.valueof(10); biginteger hundred = biginteger.valueof(100); biginteger 5 = biginteger.valueof(5); (int = 1; <= n; i++) { if (p * p == i) { p++; continue; } biginteger x = squareroot(i, p, ten, hundred, five); char[] digits = x.tostring().tochararray(); (int j = 0; j <= p - 1; j++) { sum += character.getnumericvalue(digits[j]); } } system.out.println(sum); scanner.close(); }}
can provided or suggestions proper usage of biginteger optimum performance?
comments on improvement of above algorithm welcomed.
biginteger ten = biginteger.valueof(10); biginteger hundred = biginteger.valueof(100); biginteger 5 = biginteger.valueof(5);
should moved outside of function squareroot
not created , initialized every time function called. make sure still accessible in function.
biginteger num; biginteger limit; biginteger a; biginteger b;
should created outside of function , should initialized on every fucntion call.
also following line
b = (b.divide(ten)).multiply(hundred).add(five);
can optimized to
b = b.multiply(ten).add(five);
Comments
Post a Comment