Multiplication of 123456789 and 987654321 is yielding in -67153019. I have used both int and long types but couldn't find the required result.
int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = n1*n2 ;
The result should be 121932631112635269 but it comes out to be -67153019.
This is because 121932631112635269 is greater than max int, so when doing n1 * n2, the result parsed to int will be garbage. The cast to Long is made after the math, when it tries to do the = with ans.
If you cast n1 and n2 to long before, doing the math you will get 121932631112635269.
int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = (long)n1 * (long)n2;
or like this:
int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = 1L * n1 * n2;
or if you change n1 and n2 types to long
edit: as Turing85 says,
the 2nd cast is superfluous
since the n1 would be cast to long before, there's no need to cast n2, since the result would be a Long. Making:
int n1 = 123456789 ;
int n2 = 987654321 ;
long ans = (long)n1 * n2;
also correct
It is due to order of operations. In your case, first JVM tries to multiply 2 ints as an int (because result of binary operation with int operands is also an int), and only then puts the result to long because the left-hand side variable has long type.
Please try this:
long ans = 1L * n1 * n2;
This should solve the overflow issue.
Related
I was trying to convert the array to integer sum=999999999999 (twelve 9) , when i am limiting the array to less than ten 9s it is giving the result but when i am giving the array of more than ten 9s it is giving an unexpected result , please explain it will be really helpful for me
int[] arr={9,9,9,9,9,9,9,9,9,9,9,9};
int p=arr.length-1;
int m;
int num=0;
for (int i = 0; i <= p; i++) {
m=(int) Math.pow(10, p-i);
num += arr[i]*m; // it is executing like: 900+90+9=999
}
this happens because you're exceeding the Integer.MAX_VALUE.
You can read about it here.
You can use instead of int a long, to store large values,
and if that is not enough for you, you can use - BigInteger
BigInteger num = BigInteger.valueOf(0);
for (int i = 0; i <= p; i++) {
BigInteger m = BigInteger.valueOf((int) Math.pow(10, p-i));
BigInteger next = BigInteger.valueOf(arr[i]).multiply(m));
num = num.add(BigInteger.valueOf(arr[i]*m));
}
A couple of things.
You don't need to use Math.pow.
for up to 18 digits, you can use a long to do the computation.
I added some extra digits to demonstrate
int[] arr={9,9,9,9,9,9,9,9,9,9,9,9,1,1,2,3,4};
long sum = 0; // or BigInteger sum = BigInteger.ZERO;
for (int val : arr) {
sum = sum * 10 + val; // or sum.multiply(BigInteger.TEN).add(BigInteger.valueOf(val));
}
System.out.println(sum);
prints
99999999999911234
Here is the sequence for 1,2,3,4 so you can see what is happening.
- sum = 0
- sum = sum(0) * 10 + 1 (sum is now 1)
- sum = sum(1) * 10 + 2 (sum is now 12)
- sum = sum(12)* 10 + 3 (sum is now 123)
- sum = sum(123)*10 + 4 (sum is now 1234)
It is because an int is coded on 4 byte so technically you can only go from -2,147,483,648 to 2,147,483,647.
Consider using the long type.
Try using long (or any other type which can represent larger numbers) instead of int.
I suggest this because the int overflows: see https://en.wikipedia.org/wiki/Integer_overflow
Because it overflows integer boundry. The maximum integer value that can be stored in Java is 2147483647. When you try to store a value greater than this, the result will be an unexpected value. To solve this issue, you can use a long data type instead of an int data type
you can read about it here and here
I have the following problem:
If n1 & n2 are natural numbers while n1 < 10 and n2 <10000.
find the summation of all digits in z where z = n1n2.
ex. n1 = 3, n2 = 10, z= 3^10 = 59049 if you sum the digits 5+9+0+4+9= 27. result =27
ex. n1 = 2, n2 = 12, z= 2^12 = 4096 if you sum the digits 4+0+9+6 = 19. result =19
And my current solution is:
public static long Solving(int n1, int n2) {
if (n1 >= 0 && n2 >= 0) {
BigInteger z = BigInteger.valueOf((long) Math.pow(n1, n2));
long sum = 0;
for (BigInteger i = z; i.compareTo(BigInteger.ZERO) > 0; i = i.divide(BigInteger.TEN)) {
sum += Integer.valueOf(String.valueOf(i.remainder(BigInteger.TEN)));
}
return sum;
}
return 0;
}
Why all cases doesn't success in that problem?
The actual problem is Math.pow(n1, n2).
Here you are treating both arguments as double and trying to calculate n1n2 which can easily cause an overflow.
Instead you can use BigInteger#pow() to get rid of overflow:
BigInteger z = BigInteger.valueOf(n1).pow(n2);
This will solve the issue.
I think you can solve this easily by doing something like this :
Step 1. Convert n1 to BigInteger
Step 2. Use native power function of BigInteger [exponent of pow function of big integer must be int]
Step 3. Convert the result back into string
Step 4. Iterate over the string and calculate the sum of digits.
Reference : https://www.tutorialspoint.com/java/math/java_math_biginteger.htm
https://www.tutorialspoint.com/java/math/biginteger_pow.htm
int d = year%100;
int c = year/100;
int valueA = (int)(((13*monthnumber)-1)/5);
int valueB = (int) d/4;
int valueC = (int) c/4;
int weekDay = (d + valueA + d + valueB + valueC - 2*c);
int remainder %= weekDay/7;
im trying to use the modulus assignment operator but keep getting a system error saying that an '=' was expected instead of '%='
code in question is the last line
please help
int remainder %= weekDay/7;
would be equivalent to
int remainder = remainder % weekDay/7;
which makes no sense since you just declared remainder, so it has no previous value.
Had you declared the remainder variable earlier, this would work :
remainder %= weekDay/7;
%= can't be used for variables that haven't had a value assigned yet.
var %= {value};
is equivalent to
var = var % {value};
But in the way you're using it, remainder hasn't had a value assigned to it yet. So it makes no sense.
You probably just meant to do this:
int remainder = weekDay % 7;
because with int remainder you are declaring a variable, and its initialisation cannot be achieved with %=
So I am doing this problem which requires to calculate the equations. At first i thought long would be enough for the range but now it has exceeded the long range and now i have to use BigInteger. I have to convert one equation but I haven't been able to
This is the equation :
count =(n2/n3)-((n1-1)/n3);
Count can be long but n1,n2,n3 should be BigInteger.
This simplifies to:
-(n1-n2-1)/n3
and in Java
BigInteger count = n1
.subtract(n2)
.subtract(BigInteger.valueOf(1))
.negate()
.divide(n3)
BigInteger seems to have a longValue() method that should be able to do the job:
http://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html
long count = (n2
.divide(n3))
.substract( (n1
.subtract(BigInteger.ONE))
.divide(n3)
).longValue()
This oneliner should do the trick...
long count;
BigInteger n1, n2, n3;
n1 = n2 = n3 = new BigInteger("1231232");
//count =(n2/n3)-((n1-1)/n3);
//count = (n2/n3)
count = (n2.divide(n3))
// -
.subtract(
//((n1-1)/n3);
((n1.subtract(new BigInteger("1").divide(n3))))
).longValue();
You can use BigInteger#valueOf(long val)
count = (BigInteger.valueOf(n2.intValue()).divide(BigInteger.valueOf(n3.intValue()))).
subtract(((BigInteger.valueOf(n1.intValue()).
subtract(BigInteger.valueOf(n1.intValue()))).
divide(BigInteger.valueOf(n3.intValue())));
I am trying to implement a basic calculation. The program take in 2 numbers, it works fine with 10 divided by 5 and give answer 2. If any smaller value divided by a larger value it will give me 0, can I have the answer in fraction?
Example 8 divided by 100 equal 8/100 rather than 0.
public class numtheory {
public static void main(String[] args) {
int n1;
int n2;
Scanner scan = new Scanner(System. in );
System.out.println("input number 1: ");
n1 = scan.nextInt();
System.out.println("input number 2: ");
n2 = scan.nextInt();
int temp1 = n1 / n2;
System.out.print("\n Output :\n");
System.out.print(temp1);
System.exit(0);
}
}
You need to convert your numbers to double:
double temp = ((double) n1) / n2;
If you want to produce a fraction, you can just print out:
System.out.println(n1 + "/" + n2);
This will print out whatever numbers you're given though, they won't be reduced.
You can reduce them yourself however with something like:
int n = n1;
int d = n2;
while (d != 0) {
int t = d;
d = n % d;
n = t;
}
int gcd = n;
n1 /= gcd;
n2 /= gcd;
And then print them out:
System.out.println(n1 + "/" + n2);
Instead of using integers, you need to use double.
This because an integer can only contain while numbers where double can contain decimal numbers.
u could change all the int to double or cast the in to double by dooing
((double) yourIntValue)
you could also get the input as a string, and parse it with
double dval=Double.parseDouble(value);