Welcome back to the weekly programming contests! If you are new to the contest or need a refresher don’t forget to read up on the rules and information Posted Here
This week’s challenge is to write a method that takes in two integers, and returns the square root of the first number with the precision of the second, as a String. The second parameter specifies the number of digits AFTER the decimal point to calculate the square root. Your method also should not round at all.
Also, if you like these weekly programming problems, please make some suggestions for the contest or specific challenges (in the main thread)! This takes time out of my Sunday and its not always fun! Using suggested challenges makes it a lot faster and easier for me.
The second parameter is the amount of digits you need after the decimal point, the only time you don’t need to carry the zeros is if that number is 0, in which case your only finding the integer value of the square root.
@meguy26
That fails for root(81, 1) -> 9 returning 21.2 instead. When the precision is small enough you are not doing enough iterations to get an accurate answer. If you initialize n to -9 this fixes this issue.
This is along the same lines. It’s slightly longer, but doesn’t error on values less than 1.
Seems to be accurate enough.
Minified (207 chars)
public static String r(int i,int p){BigDecimal v=new BigDecimal(i).setScale(p),l=v,t=BigDecimal.ONE,d=t.add(t);while(i>0&&!l.equals(l=t=v.divide(t,1).add(t).divide(d,1)));return i<0?"NaN":l.toPlainString();}
178 chars if we can assume the input is greater than 0 like the post above
public static String r(int i,int p){BigDecimal v=new BigDecimal(i).setScale(p),l=v,t=BigDecimal.ONE,d=t.add(t);while(!l.equals(l=t=v.divide(t,1).add(t).divide(d,1)));return""+l;}
Readable
public static String sqrt(int in, int places)
{
BigDecimal val = new BigDecimal(in).setScale(places);
BigDecimal last = val;
BigDecimal test = BigDecimal.ONE;
BigDecimal two = test.add(test);
while (in > 0 && !last.equals(last = test))
{
test = test.add(val.divide(test, RoundingMode.FLOOR)).divide(two, RoundingMode.FLOOR);
}
return in < 0 ? "NaN" : last.toPlainString();
}