Home › Forums › Programming › Find Missing Number In A Random Rang of Unordered Numbers: Cpp
Tagged: cpp, missing number, random rang
- This topic has 2 replies, 2 voices, and was last updated 12 years, 8 months ago by Satish.
- AuthorPosts
- February 1, 2012 at 11:06 am#1327SatishKeymaster
Solve this simple problem using C++
I have 1 to 100 numbers jumbled, i mean they are not in sequence..
example: 99,2,45,12,66,…like this numbers are jumbled and numbers are within 100 only..
I have one number missed..so now i have 99 numbers jumbled,,i want to find that missed number..find it..example: 8,3,1,5,9,2,6,7,10 (numbers are jumbled, and numbers between 1 to 10)
missed number is: 4
February 1, 2012 at 11:11 am#1328ShwethaMember#include<iostream.h> #include<conio.h> void main() { //Numbers jumbled of range 10 is given.find the missed number i,e 5 //Dont prompt the user to enter the range.Just count the number of numbers //they given and then add a one to it. You will get the range //in our problem, we are given Array a[] with 9 elements, // therefore range is 9+1 = 10 int a[9] = {8,2,6,1,3,7,9,4,10}; int Current_sum = 0,Needed_Sum=0, Range=10, Missed_num; // range = no.of elements in a[] + 1 i,e 9 + 1 = 10 clrscr(); Needed_sum = range(range+1)/2; // Natural numbers sum formula n(n+1)/2 for(int i=0; i<9; i++) Current_sum = current_sum + a[i]; //else you can use simply Current_sum += a[i]; Missed_num= Needed_sum-Current_sum; cout<<"Missed number is: "<<Missed_num; getch(); }
1) In the above problem, you are given Random numbers between 1 to 10, with a number missed. Mean you are given only 9 numbers, find the 10th one
i,e a[9]= 8,2,6,1,3,7,9,4,10
In real the problem statement is simple as below,
a[9]= 1,2,3,4,?,6,7,8,9,10
now numbers are not in random order, so easily your common sense finds the missing number as 5.
now make the machine to have the same common sense with your logics..
2) First find the sum of given numbers and name it as Current_sum.
Current_sum = 8+2+6+1+3+7+9+4+10
Current_sum = 50
3) Secondly find the sum of 1 to 10(Range) numbers using natural numbers sum formula n(n+1)/2 and name it as Needed_sum
here n is range i,e 10
Needed_sum = 10(10+1)/2
Needed_sum = 55
4) Missed_num = Needed_sum – Current_sum
Missed_num = 55 – 50
Missed_num = 5
# Try the same by changing the ‘Range’ and accepting the random numbers from user instead of declaring the Array elements directly.
# Intially, Normally all will try to sort the given random numbers into linear and then they try to compare each number to find the missed one.
This method is ok with 10 range, 20 range…what about 100, 1000 range?
It is very time consuming and inefficient method.
Think simple…April 12, 2012 at 7:49 am#1548SatishKeymasterExcellent Shwetha.. thanks a lot for the clean code
- AuthorPosts
- You must be logged in to reply to this topic.