I am trying to figure out why the following is not correctly calculating
x = Math.pow(w,e);
When I calculate it in Java, I get 1075, but I am supposed to get 779.
int e = 17;
int w = 803;
int n = 2773;
double x = 0;
x = Math.pow(w,e) % n;
System.out.println(x);
double floating point numbers have 53 bits of precision, which is not enough to store the exact value of a huge number like 80317. To do modular exponentiation in Java, you can use the modPow method on BigIntegers.
As (803^17) is a very big number so you have to use the BigInteger datatype for the variables used here instead of int or double datatype. We cannot convert the integer or double variable to a BigInteger variable.
So, the program will be :
import java.math.BigInteger;
public class JavaPow {
public static void main(String[] args)
{
BigInteger e = new BigInteger("17");
BigInteger w = new BigInteger("803");
BigInteger n = new BigInteger("2773");
BigInteger x;
x = w.modPow(e,n);
System.out.println(x);
}
}
Related
This question already has an answer here:
Why in one case multiplying big numbers gives a wrong result?
(1 answer)
Closed 2 years ago.
I am new to Java and when I was trying to find power of number without Math.pow method I realized the answer was not right. And I want to learn why?
public class Main() {
int x = 1919;
int y = x*x*x*x;
public static void main(String[] args) {
System.out.println(y);
}
}
Output: 2043765249
But normally answer is: 13561255518721
If you go step by step, you'll see that at a moment the value becomes negative, that's because you reach Integer.MAX_VALUE which is 2^31 -1
int x = 1919;
int y = 1;
for (int i = 0; i < 4; i++) {
y *= x;
System.out.println(i + "> " + y);
}
0> 1919
1> 3682561
2> -1523100033
3> 2043765249
You may use a bigger type like double or BigInteger
double x = 1919;
double y = x * x * x * x;
System.out.println(y); // 1.3561255518721E13
BigInteger b = BigInteger.valueOf(1919).pow(4);
System.out.println(b); // 13561255518721
You're using an int for the answer, you're getting a numeric overflow.
Use double or long or BigInteger for y and you'll get the right answer.
public class Main {
public static void main(String[] args) {
System.out.println(Math.pow(1919, 4));
System.out.println((double) 1919*1919*1919*1919);
}
}
Outputs the same value.
Use long instead of int
public class Main{
public static void main(String[] args) {
long x = 1919;
long y = x*x*x*x;
System.out.println(y);
}
}
Read about variables in Java.
Im not understanding casting in java, char casting in particural. I'm not able to predict the outcome of this code,since I don't understand what the casting of char will "reproduce".Some explanation would be great! Thanks
public class test {
public static void main(String[] args) {
int u = 10;
double v = 22.105;
byte w = 100;
char x = 'a';
float y = 20.5f;
short z = 50;
double d_Value = (float) ((char) (u/v) + y);
Out.print(d_Value);
}}
char is an integer-based data type, so you'd lose the precision from the double result on u/v, giving you a 0 number (or the \0 char). Then it adds 20.5F for the final result: 20.5.
Casting is a higher precedence than most operators in the language, so that cast is relevant before the + operation.
This question already has answers here:
Integer division: How do you produce a double?
(11 answers)
Closed 3 years ago.
I am trying to write a formula for one of my functions where I need to raise my X to power of Y. The values I am working with are really small and will get rounded up as soon as I use pow function of Math, BigInteger and BigDecimal.
For example if I use the following values it will return 1000 whereas it should return 1006.931669!
T0 = 1000, TN = 1, k = 1, N = 1000
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
They are being divided in integer arithmetics. So dividing integer a by integer b you get how many times b fits into a, If the types of the operands are double, then "real" division is performed.
double X = (finalTemp/(double)initialTemp);
double A = Math.pow(X, (k/(double)n));
double tk = initialTemp * A;
the output is correct according to calculator
public class Main
{
public static void main(String[] args) {
double finalTemp = 1.0;
double initialTemp = 1000.0;
double k = 1.0;
double n = 1000.0;
double X = (finalTemp/initialTemp);
double A = Math.pow(X, (k/n));
double tk = initialTemp * A;
System.out.println(tk);
}
}
output is 993.1160484209338
I want to find the closest fraction equal to 16/76. Whenever i run this i get 1 no matter what. I am doing this for Java class in school.
public class ClassOne {
public static double limit = 16/76;
public static double difference = 1;
public static double numer = 1;
public static double denom = 1;
public static void main(String[] args)
{
for(int i = 1;i<=100;i++)
{
for(int x = 1;x<=100;x++)
{
double temp = limit-(double)(x/i);
System.out.println((x/i));
if(Math.abs(temp) < difference && x/i != 16/76){difference = temp;numer = x; denom = i;
System.out.println("hi");}
}
}
System.out.println(numer + " " + denom);
}
}
A few problems
Use (double)x/(double)i where needed - probably assign to a temp
difference=temp should be difference=Math.abs(temp) or put the abs on the original temp computation
x/i = 16/76 is subject to floating point errors and so may not be hit when you want. May want to use something like 16*i != 76*x which can be computed in integers. I get 21 100.
You're encountering integer division here:
limit - (double)(x/i)
...and here:
public static double limit = 16/76;
Both x and i are int. The cast here will take effect after the division operation has taken effect.
Change your cast so that it applies immediately to one of the variables instead:
limit - ((double)x)/i
Also, consider wherever else you're doing any quotient that isn't with a floating point number (i.e. has a decimal after it or is explicitly cast to a double) - if you need it to be a floating point number, then use the appropriate cast.
I am currently trying to solve this problem as described here:
http://uva.onlinejudge.org/external/1/113.pdf
The plan was to implement a recursive function to derive the solution. Some of the code here comes from Rosetta code for determining the nth root.
// Power of Cryptography 113
import java.util.Scanner;
import java.math.BigDecimal;
import java.math.RoundingMode;
// k can be 10^9
// n <= 200
// p <= 10^101
class crypto {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
// Given two integers (n,p)
// Find k such k^n = p
int n = in.nextInt();
BigDecimal p = in.nextBigDecimal();
System.out.println(nthroot(n,p));
}
}
public static BigDecimal nthroot(int n, BigDecimal A) {
return nthroot(n, A, .001);
}
public static BigDecimal nthroot(int n, BigDecimal A, double p) {
if(A.compareTo(BigDecimal.ZERO) < 0) return new BigDecimal(-1);
// we handle only real positive numbers
else if(A.equals(BigDecimal.ZERO)) {
return BigDecimal.ZERO;
}
BigDecimal x_prev = A;
BigDecimal x = A.divide(new BigDecimal(n)); // starting "guessed" value...
BigDecimal y = x.subtract(x_prev);
while(y.abs().compareTo(new BigDecimal(p)) > 0) {
x_prev = x;
BigDecimal temp = new BigDecimal(n-1.0);
x = (x.multiply(temp).add(A).divide(x.pow(temp.intValue())).divide(new BigDecimal(n)));
}
return x;
}
}
And here is the resulting error code:
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1616)
at crypto.nthroot(crypto.java:38)
at crypto.nthroot(crypto.java:24)
at crypto.main(crypto.java:19)
Anybody here for a working code snippet? Here we go:
public final class RootCalculus {
private static final int SCALE = 10;
private static final int ROUNDING_MODE = BigDecimal.ROUND_HALF_DOWN;
public static BigDecimal nthRoot(final int n, final BigDecimal a) {
return nthRoot(n, a, BigDecimal.valueOf(.1).movePointLeft(SCALE));
}
private static BigDecimal nthRoot(final int n, final BigDecimal a, final BigDecimal p) {
if (a.compareTo(BigDecimal.ZERO) < 0) {
throw new IllegalArgumentException("nth root can only be calculated for positive numbers");
}
if (a.equals(BigDecimal.ZERO)) {
return BigDecimal.ZERO;
}
BigDecimal xPrev = a;
BigDecimal x = a.divide(new BigDecimal(n), SCALE, ROUNDING_MODE); // starting "guessed" value...
while (x.subtract(xPrev).abs().compareTo(p) > 0) {
xPrev = x;
x = BigDecimal.valueOf(n - 1.0)
.multiply(x)
.add(a.divide(x.pow(n - 1), SCALE, ROUNDING_MODE))
.divide(new BigDecimal(n), SCALE, ROUNDING_MODE);
}
return x;
}
private RootCalculus() {
}
}
Just set SCALE to however precise you need the calculation to be.
That is expected if the resulting mathematical decimal number is non-terminating. The Javadocs for the 1-arg overload of divide state:
Throws:
ArithmeticException - if the exact quotient does not have a terminating decimal expansion
Use another overload of the divide method to specify a scale (a cutoff) (and a RoundingMode).