-1

I am solving some tasks from school olimpiads, and I got stuck on one question. I found the solution for the task, but my solution requires square rooting. My code works fine for first 12 inputs, but then it gives wrong answers. I guess that it is due to extremely large inputs, which can be as large as 10^400000. So I would like to know if there are ways to calculate whole number parts of square roots of these extremely large inputs in C. Here is the code:

#include <math.h>
#include <stdio.h>
#include <stdlib.h>
int main(){
    long long n;
    scanf("%lld", &n);
    long long ans;
    ans = sqrtl(n-1);
    long long result;
    result = ans+1-llabs(n-ans*ans-(ans+1));
    printf("%lld\n", result);
    return 0;
}
ar kang
  • 95
  • 9

1 Answers1

0

In a nutshell, you can roll a long square root algorithm by the dichotomic method as follows:

  • choose a long number representation (array of unsigned ints);

  • implement long addition and subtraction (pretty trivial, except for carries);

  • implement halving (also requires some care for carries);

  • implement long comparison (similar to subtraction).

[Note that addition allows you to implement doubling and quadrupling, and halving also yields division by four.]

Then set d= 1 and repeatedly double d until d² > N. (Every time you double d, you quadruple .)

Next, set a= 0 so that the invariant

a² ≤ N < (a + d)²

is established, and repeatedly halve d while keeping the invariant. This is achieved by

d= d/2; if N < (a + d)², set a= a + d; else keep a unchanged.

In the end, you will narrow down to

a² ≤ N < (a + 1)²

so that a is the integer square root.

To evaluate the condition

N < (a + d)² = a² + 2ad + d²,

or

N - a² < 2ad + d²,

it suffices to keep a trace of the terms N - a², 2ad and and update them as you modify d or a. This only takes the aforemetioned primitive operations.

Yves Daoust
  • 48,767
  • 8
  • 39
  • 84