Devender Goyal
Devender Goyal

Reputation: 1788

Modulo operator usage while dealing with doubles

I have to find the value of ( 1+sqrt(3) )^n where n < 10^9.As this number can be very large we have to print the ans%1000000007. I have written the following function for this.

double power(double x, int y)
{
    double temp;
    if( y == 0)
       return 1;
    temp = power(x, y/2);
    if (y%2 == 0)
       return temp*temp;
    else
    {
       if(y > 0)
           return x*temp*temp;
       else
           return (temp*temp)/x;
    }
}

Now, I unable to understand how to take care of the modulo condition.Can somebody please help.

Upvotes: 1

Views: 319

Answers (3)

huseyin tugrul buyukisik
huseyin tugrul buyukisik

Reputation: 11920

modulo needs integer type, you could use union for your double type unioned with an integer to use the modulo(if this is C)

Upvotes: 0

Eric Postpischil
Eric Postpischil

Reputation: 222933

This approach is infeasible. As shown in this question, you would need hundreds of millions of decimal digits more precision than the double type supplies. The problem you are actually trying to solve is discussed here. Are you two in the same class?

Upvotes: 0

Daniel Fischer
Daniel Fischer

Reputation: 183908

You can't do that. You could use fmod, but since sqrt(3) cannot be exactly represented, you'd get bogus values for large exponents.

I'm rather confident that you actually need integer results ((1 + sqrt(3))^n + (1 - sqrt(3))^n), so you should use integer math, exponentiation by squaring with a modulo operation at each step. cf. this question

Upvotes: 1

Related Questions