Find missing number.
Find missing number from given range of 1 to n.
Solution:
Algorithm:
// Java program to find missing Number
class Main {
// Function to find missing number
static int findMissingNo(int a[], int n)
{
int i, total;
total = (n + 1) * (n + 2) / 2;//calculates total for original range
for (i = 0; i < n; i++)
total -= a[i];//this will yield the missing number by continuously subtracting elements
return total; // from total
}
/* program to test above function */
public static void main(String args[])
{
int a[] = { 1, 2, 4, 5, 6, 7, 8 };
int miss = findMissingNo(a, 7 );
System.out.println(miss);
}
}
Solution:
Algorithm:
- Calculate the sum of first n natural numbers as total= n*(n+1)/2
- create a variable sum to store the sum of array elements.
- Traverse the array from start to end.
- Update the value of sum as sum = sum + array[i]
- print the missing number as total – sum
// Java program to find missing Number
class Main {
// Function to find missing number
static int findMissingNo(int a[], int n)
{
int i, total;
total = (n + 1) * (n + 2) / 2;//calculates total for original range
for (i = 0; i < n; i++)
total -= a[i];//this will yield the missing number by continuously subtracting elements
return total; // from total
}
/* program to test above function */
public static void main(String args[])
{
int a[] = { 1, 2, 4, 5, 6, 7, 8 };
int miss = findMissingNo(a, 7 );
System.out.println(miss);
}
}
Comments
Post a Comment