NeverMa573r's blog

By NeverMa573r, history, 15 months ago, In English

What is the difference between the prewritten sqrt function that I used here : https://codeforces.me/contest/1737/submission/222667221 and my own written sqrt function that I wrote here : https://codeforces.me/contest/1737/submission/222667916?

I understand stuff about precision and things like that, but I'm just rounding down, so even if something is like 2.0000067 it should still yield the correct answer. Please explain! I feel like this just happens over and over again: everytime I use sqrt(x) it always fails to get AC and I have to write my own sqrt function, even if my algo is correct.

  • Vote: I like it
  • +2
  • Vote: I do not like it

| Write comment?
»
15 months ago, # |
Rev. 3   Vote: I like it +1 Vote: I do not like it
    public long sqrt(long x) {
    	long start = 0, end = (long)3e9, ans = 1;
        while(start<=end){
            long mid = (start+end)/2;
            if(mid*mid<=x){
                ans = mid;
                start = mid+1;
            }
            else
                end = mid-1;
        }
        return ans;
    }

Inbuilt square root functions loose precision for bigger numbers like 1e18 in cpp you can use sqrtl (that gives correct ans always) or this function