Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!

# Java Math issue incorrect output

Mohtashim Shaikh
Ranch Hand
Posts: 43
51^43Mod77 in scientific calculator gives 2 as the output however,

(int)(Math.pow(51,43)%(double)77) gives 12 which should be 2 instead.

Wouter Oet
Saloon Keeper
Posts: 2700
I guess that the integer overflows resulting in wrong output.

Stephan van Hulst
Bartender
Posts: 5797
61
Actually, int isn't the culprit, double is. Double simply isn't big enough to represent 51^43 at integer precision.

Instead, try BigInteger to do the calculation.

Mohtashim Shaikh
Ranch Hand
Posts: 43
It works !!!

However, I do not wish to use modPow

How can i (a raiseto b) Mod c without using modPow?

when a,b and c are BigIntegers

Ulf Dittmer
Rancher
Posts: 42967
73
However, I do not wish to use modPow

Why not?

Campbell Ritchie
Sheriff
Posts: 48930
58
You can write your own method to raise numbers to their powers.

Mohtashim Shaikh
Ranch Hand
Posts: 43
Campbell Ritchie wrote:You can write your own method to raise numbers to their powers.

Does that mean there is no way inbuilt methods trick to achieve this ?

Jesper de Jong
Java Cowboy
Saloon Keeper
Posts: 15276
38
• 1
Yes, there is, but you just said that you don't want to use it...

Besides modPow, class BigInteger also has separate pow and mod methods. Lookup the API documentation of class BigInteger.

Rob Spoor
Sheriff
Posts: 20527
54
Oddly enough the pow method takes an int, not a BigInteger like modPow.

Mohtashim Shaikh
Ranch Hand
Posts: 43
Rob Spoor wrote:Oddly enough the pow method takes an int, not a BigInteger like modPow.

Thats the very reason I asked if there isany inbuilt functionality inorder to achieve modPow. If so can someone help me with the code syntax.

Stephan van Hulst
Bartender
Posts: 5797
61
Um yes? It's the modPow() method in BigInteger. Why don't you use it?

Rob Spoor
Sheriff
Posts: 20527
54
Or implement pow yourself. It's not that hard. Inefficient maybe, with all the BigInteger objects that are created, but not hard.

Mohtashim Shaikh
Ranch Hand
Posts: 43
Stephan van Hulst wrote:Um yes? It's the modPow() method in BigInteger. Why don't you use it?

I wish to separate the pow and the mod functionalities . Not sure how could I ?

fred rosenberger
lowercase baba
Bartender
Posts: 12122
30
Mohtashim Shaikh wrote:
Stephan van Hulst wrote:Um yes? It's the modPow() method in BigInteger. Why don't you use it?

I wish to separate the pow and the mod functionalities . Not sure how could I ?

1) Write your own pow method
2) Write your own mod method.

OR

1) Use BigInteger's pow method
2) Use BigInteger's mod method