Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Pinterest
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Find two Missing Numbers in a Sequence of Consecutive Numbers

Objec­tive : Write an algo­rithm to find two Miss­ing Num­bers in a Sequence of Con­sec­u­tive Numbers

Input:  Array, arrA[] with two miss­ing num­bers and Range

Out­put : Two miss­ing numbers

Approach:

    • Approach is very sim­ple, Add all the given num­bers say S
    • Cal­cu­late sum of N num­bers by for­mula n(n+1)/2 , say N
    • Find sum of two miss­ing num­bers a+b = N-S

  • Now take the prod­uct of all given num­bers say P
  • Now take the prod­uct of N num­bers , say Np;
  • Find the prod­uct of two miss­ing num­bers ab = Np–P
  • Now we have a+b and ab , we can eas­ily cal­cu­late a and b

Exam­ple :

Given array : {10,2,3,5,7,8,9,1}; Range : 10

N (Sum of 1 to 10 ) = 55

S (Sum of given elements ) = 45

a+b = 10------------------------------------(1)

Np(Product of 1 to 10) = 3628800

P(Product of given elements) = 151200

So a*b = 24---------------------------------(2)

Now we have two equations and two variables, if we solve we will get values 6 and 4.

Com­plete Code:


Out­put:

Missing numbers are :6 and 4

 

You may also like...

  • kapil

    The exam­ple is very good, just a small bug at line 30 in the snip­pet, it should be (s*2) not (s*s) in the equa­tion
    diff­Sqr = (int)Math.sqrt((s*s)-4*product)