I have given two number a
and b
.I have to Calculate (a^b)%1000000007
.How Can i calculate for floating point numbers. Ex:
a= 7.654 and b=10000
Here is my Code will %
work :
public static double super_pow(double A , long B){
double o=1;
while(B>0){
if((B&1)!=0) o*=A;
A*=A;
B/=2;
o%=mod;
A%=mod;
}
return (o)%mod;
}
Yes, in Java you can use the % operator on floating point types.
You will have problems with the exponent though: You can't use
%
to reduce the intermediate results because modulo does not distribute over floating point multiplication:(a*b)%c
is not(a%c)*(b%c)
. If you try to compute 7.654^10000 directly you will getinfinity
; it exceeds the maximum value fordouble
. Even if it didn't you couldn't trust the lowest digits of the result because they are pure noise created by rounding and representation error.You could use a library that implements exact arithmetic, such as java.math.BigDecimal, but that will cost a lot in terms of execution time and memory. If you think you need to do this calculation as a part of a bigger problem, probably you should take a step back and find another way.
Edit: Here's the result with
BigDecimal
:Is
%
Modulo?That depends on language you are using. But In general floating point values does not know modulo operation. You can compute it on your own. Let assume positive floating numbers
a=7.654
andb=10000.0
sofloor(x)
rounds down to nearest less or equal number tox
d
holds the floating division resultr
holds the remainder (modulo)Another example
a=123.456
andb=65
This can be used for integer and decimal values of
a,b
but beware the floating point unit performs rounding and can loose precision after few digits... If I remember correctly 64 bitdouble
variables are usually usable maximally up to18
digits.[Edit1] hmm you reedited the question to completely different problem
So you are searching for
modpow
. You can google for java implementation ofmodpow
. For example hereYou can find mine implementation in C++ on 32 bit integer arithmetics but with static modulo prime with specific properties. Still if you change all the
to
d=d%p;
it would work for any modulo. you will needmodpow,modmul,modadd,modsub
.In java you can use the modulo operation for floats/doubles (How do I use modulus for float/double?)
If you have to calculate (a^b)%1000000007 you can use
double
fora
andb
(biggest integer that can be stored in a double), this makes exponentiation easier, use thepow()
method (http://www.tutorialspoint.com/java/number_pow.htm)Alternatively you can typecast (loss of precision possible !) the result of a^b to
long
and then useWhat is the modulo operator for longs in Java?