Reputation: 3
I wanted to find the missing number in series so i thought a simple idea why not add all the numbers in array which are in series and hold it in one variable and then calculate the sum of series by formula Sn=n/2(a+l)
but while calculating the series sum i am getting some error.
public class Missing {
public static void main(String[] args) {
int ar [] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int sum = 0; int total=0;
for(int num: ar)
{
sum = sum+num;
}
int n = ar.length;
int a = ar[0];
int l =ar[ar.length-1];
total = [n/2*(a+l)];
System.out.print("The missing number is "+(sum-total));
}}
total = [n/2*(a+l)]; ............................(1)
This is where i am getting error.
Upvotes: 0
Views: 86
Reputation: 256
If you don't want to use my above logic. You have to make changes to your code: Edit this:
int n = ar.length+1;
n has been assigned ar.length + 1 because that +1 is needed to compensate for the missing element in the array list
Also, the formula has not been correctly written into the code:
total = (n* (a + l))/2;
If you first divide n by 2 then, it will truncate the places after decimal point because n is an integer not a floating number. So, your logic would fail when n is not even.
And lastly, the missing number would be (sum-total) not the other way around because 'total' contains the missing number and 'sum' does not.
System.out.print("The missing number is "+(total-sum));
Upvotes: 0
Reputation: 256
You can use the below logic which is much simpler to use and understand
for(int i=0;i<ar.length-1;i++)
{
if(ar[i]!=ar[i+1]-1)
{
System.out.print("The missing number is "+(ar[i]+1)+"\n");
break;
}
}
Upvotes: 1
Reputation: 5185
The first thing is in total = [n/2*(a+l)];
[]
is not valid syntax in this context. The second thing I noticed, is that your formula to calculate the sum seems odd, maybe you meant Sn = (n * (a + l)) / 2?
. After making those two changes the code should look as follows:
public class Missing {
public static void main(String[] args) {
int ar [] = {1,2,3,4,5,6,7,8,9,10,11,12,13};
int sum = 0;
for(int num: ar)
{
sum = sum+num;
}
int n = ar.length;
int a = ar[0];
int l =ar[ar.length - 1];
int total = (n * (a + l)) / 2;
System.out.print("The missing number is "+(sum - total));
// outputs 0 which is correct nothing is missing
// Now if you remove say 12 from the array
// by changing the array to int ar [] = {1,2,3,4,5,6,7,8,9,10,11,0,13};
// you should get back -12 which means 12 is missing
}
}
Upvotes: 0