Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.
static void miniMaxSum(int[] arr) {
int summin=0;
int summax=0;
for (int i=0; i< 5; i++) {
for (int j=4; j>i; j--) {
if(arr[i]>arr[j]){
int c=arr[i];
arr[i]=arr[j];
arr[j]=c;
}
}
}
for (int i=0; i<4; i++) {
summin=summin+arr[i];
}
for (int i=1; i<5; i++) {
summax=summax+arr[i];
}
System.out.print(summin+" "+summax);
}
My code only works correctly enter image description here with 5/15 testcases. I want to sort the array and then calculate the result. The "min" result is correct, but the "max" result is a negative integer so it's wrong. I found the problem is caused by the last element after sorted. Using Netbeans, I calculated the sum of all element in the array. After 4 first elements, the sum still was a positive int, but when 5th element added, the sum changed into a negative int. I don't know why, can someone help me please?
You are exceeding the range of integer and the value is overflowing to the negative side. If you want to test with big numbers use long datatype.
Int Datatype Rang:
-2,147,483,648 to 2,147,483,647 The int data type is a 32-bit signed Java primitive data type. A variable of the int data type takes 32
bits of memory. Its valid range is -2,147,483,648 to 2,147,483,647
(-231 to 231– 1).
I guess you should use long as summin and summax, that would solve your problem (you have negative values because you sum max is more than max integer value)
Related
I have a very long array in a Java program (300 000+ unsorted integers) and need to calculate the minimum absolute difference between any two numbers inside the array, and display the absolute difference and the corresponding pair of numbers as an output. The whole calculation should happen very quickly.
I have the following code, which would usually work:
private static void calcMinAbsDiff(int[] inputArray)
{
Arrays.sort(inputArray);
int minimum = Math.abs(inputArray[1] - inputArray[0]);
int firstElement = inputArray[0];
int secondElement = inputArray[1];
for (int i = 2; i < inputArray.length; i++)
{
if(Math.abs(inputArray[i] - inputArray[i-1]) < minimum)
{
minimum = Math.abs(inputArray[i] - inputArray[i-1]);
firstElement = inputArray[i-1];
secondElement = inputArray[i];
}
}
System.out.println("Minimum Absolute Difference : "+minimum);
System.out.println("Pair of Elements : ("+firstElement+", "+secondElement+")");
}
However, the output I receive is all 0s. I believe this is because the array is way too long.
If you have two or more zeros and no negative integers in your dataset, then your output is expected. After sorting, then inputArray[0] and inputArray[1] would both be 0, and the difference would be 0. No other pair of adjacent elements would have an absolute difference less than 0, so minimum, firstElement, and second Element would all be 0 at the end of the algorithm.
If you really have no zeros in your dataset, or if you do have negative integers, then you may have an initialization problem. Check this thread:
Why is my simple Array only printing zeros in java?
If that's not it, then only other thing I can think of is that you have a problem in the previous scope causing the data to get zeroed out.
I would try printing samples of your dataset at various points to see exactly where/when it's getting zeroed.
If you still have trouble, then post more info on the dataset and the scope which calls this function to help us see what's going on. Let us know how you make out!
This question already has answers here:
Count the number of set bits in a 32-bit integer
(65 answers)
Closed 7 years ago.
Doing a question on codility and was Asked to take two numbers and get the product. Then get the binary repesentation of that number and count the number of one's that are in the binary number.
My code is
return method(int a, int b)
{
int count=0;
int num;
num = a* b;
while(num>0)
{
if(num %2 ==1)
{
count++;
}
num = num >> 1;
}
return count;
}
Yet it only gives 50% correctness. Can anyone explain this. Is there something i missed that i should be aware off.
Using the modulo operator won't correctly count the bits in a negative number. Use "num & 1" instead. Also, make sure you're using unsigned right shifts or a negative number may produce an infinite loop.
And as Lashane said, use a 64 bit product if possible.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm trying to figure how to find the largest number in an array of random numbers.
So far I cant manage to get it right.
Its an array[50] and the random, numbers are between 0-100.
Thanks!
Loop through the array and keep track of the largest number found already in an int variable.
public int findMax(int[] numbers)
{
int max = 0;
for (int i = 0; i < numbers.length; ++i)
if (numbers[i] > max) max = numbers[i];
return max;
}
(You can also initialize max to int.MIN_VALUE or something if it helps behave more suitably in the case where an empty array is passed in.)
Use:
java.utils.Arrays.sort(yours_array);
int largest = yours_array[yours_array.length - 1] ;
Collections.max and you can use it as follows with a raw array:
List<Integer> triedArray = new ArrayList<Integer>();
ArrayUtils.addAll(intArray);
This does add a dependency on commons-lang, though.
Assuming the int[] is named array
Try to use a loop like the following:
int biggest = array[0]
for(int a = 1; a < array.length; a++){
if(array[a] > biggest){
biggest = array[a]
}
}
At the end, your variable biggest will hold the largest value in the array.
public static void main(String[]args){
int A[]={2,4,6,9,5,4,5,7,12,15,21,32,45,5,6,7,12};
int multi= 1;
for (int i=0; i<A.length; i++) {
multi *= A[i];
}
System.out.println("The product of the numbers in the array is " + multi );
//I keep getting a negative value but when I shorten the array
//to a few numbers I don't have any problems.
}
That's called overflow.
An integer overflow occurs when an arithmetic operation attempts to create a numeric value that is too large to be represented within the available storage space. [Wikipedia - Integer Overflow]
ints can represent a maximum of (2^32)-1. Your multiplication gives a result that is higher than that value, so it generates overflow.
Change multi type to long and you won't have this problem (but only for that particular case: if you exceed the maximum value representable by a long, you'll have that problem again)
As said, changing the type to long will only postpone the problem, you can solve it by using a BigInteger, which can handle arbitrary-precision integers.
But use it only if you really have to. If you know that your app will do calculations without exceeding the long max representable value, then use a long, as the BigInteger is not a primitive and will be much slower than a long.
Start by declaring multi as a long. When a value exceeds Integer.MAX_VALUE i 'overflows' and becomes negative. The maximum integer value is just more than 2 billion, so it happens quite soon.
You encounter a negative value, it is because the multi value exceeds the Max value of Integer (2^31 -1).
You need to make the change as follows:
From
int multi= 1;
To
long multi= 1;
try this
public static void main(String[]args){
int A[]={2,4,6,9,5,4,5,7,12,15,21,32,45,5,6,7,12};
long multi= 1;
for (int i=0; i<A.length; i++) {
multi *= A[i];
}
System.out.println("The product of the numbers in the array is " + multi );
//I keep getting a negative value but when I shorten the array
//to a few numbers I don't have any problems.
}
for the Given below code after int Input Value of 46348 i am getting ArrayIndexOutOfBoundsException. I am given Condition in for loop that keeps the array limits. But somehow i am getting this exception and i unable to figure it out. And my requirement is find all primenumbers below given number.
Scanner sc = new Scanner(System.in);
int n= sc.nextInt();
int[] arr= new int[n+1];
for(int i=2;i<=n;i++)
{
if(arr[i]==0)
{
for(j=i;j*i<=n;j++)
arr[j*i]=1; // Here i am getting Exception
}
}
Input:
46349
Output:
java.lang.ArrayIndexOutOfBoundsException: -2146737495
502802
Thanks.,
You have encountered an arithmetic overflow.
In Java, int data type is a 32-bit signed integer, which means it can have values between -2147483648 and 2147483647.
On this line:
for(j=i;j*i<=n;j++)
If i is 46349 then j becomes 46349, too. If you multiply 46349 by 46349, you get 2148229801, which is greater than 2147483647, so the integer overflows and becomes -2146737495. Naturally, it is less than 46349, so the check in the for-loop passes. But you cannot index an array with a negative value in Java, that's why you get the ArrayIndexOutOfBoundsException.
Range check your input value for n < 46340, or if it really needs to work with n = 46349 input, switch to long data type, which will work up to n = 3037000499.
46349 * 46349 is too big to use as the index of a Java Array. The index is just a 32-bit signed integer, so has a maximum value of 2,147,483,648.
It passes the < n check because it overflows and comes back negative, so it is in fact less than n, but a negative number is not a legal array index.