1

My code for finding 10th decimal digit of square root of 2.

#include <stdio.h>
unsigned long long int power(int a, int b);
unsigned long long int root(int a);
int main()
{
    int n;
    n=10;

    
    printf("%llu \n",root(n));
    
    return 0;
}

unsigned long long int power(int a, int b)
{   
    int i;
    unsigned long long int m=1;
    for (i=1;i<=b;i++)
    {
        m*=a;
    }
    return m;

}

unsigned long long int root(int a)
{
    unsigned long long int c=1;
    int counter=1;
    while(counter<=a)
    {
        c*=10;
        while(power(c,2)<=2*power(10,2*counter))
        {
            c++;
        }
        c-=1;
        counter++;
    }
    return c;

}

I have tried the same algorithm in python. It can find the 10th decimal digit of $sqrt{2}$ immediately. However, while doing C, I have waited for 10 mins but without a result.

kile
  • 141
  • 1
  • 7
  • Does this answer your question? [Why does 10 digits number become 9,999,999,999?](https://stackoverflow.com/questions/64628285/why-does-10-digits-number-become-9-999-999-999) – phuclv Nov 01 '20 at 10:40

3 Answers3

1

you have overflow(s)

when counter values 10 you try to compute power(10,20) but even long long on 64 bits are not enough large, so you loop in

while(power(c,2)<=2*power(10,2*counter)){
   c++;
 }

for a long time (may be without ending)

Having long long on 64 bits allows to compute the result for n valuing up to 9

bruno
  • 32,421
  • 7
  • 25
  • 37
1

Exceed the range that the data can represent. when counter is equal to 10,2*power(10,2*counter) exceeds the range that unsigned long long int can represent. Python supports large number calculations, unlimited digits

Gerrie
  • 736
  • 3
  • 18
1

Python handles big numbers for you. [1]

Although, as you say that you are getting the answer "immediately", your algorithm in python is not probably the same as the one you used in C.

@bruno's answer already explains why you are not getting the expected results in C.

[1] Handling very large numbers in Python

Mihir Luthra
  • 6,059
  • 3
  • 14
  • 39