FindMissingNumber { protected static Number findMultiplicationPattern(BigDecimal[] numbers) { if ( numbers == null || numbers.length < MIN_NUMBER_OF_RESTRICTIONS ) { return null; } try { BigDecimal gap = null; Number missingNumber = null; BigDecimal a = numbers[0]; BigDecimal b = numbers[1]; BigDecimal c = numbers[2]; BigDecimal d = numbers[3]; if ( b.divide( a ).equals( c.divide( b ) ) ) { gap = b.divide( a ); } else if ( c.divide( b ).equals( d.divide( c ) ) ) { gap = c.divide( b ); } else if ( b.divide( a ).equals( d.divide( c ) ) ) { gap = b.divide( a ); } else { return null; } BigDecimal first = null; BigDecimal second = null; for ( int i = 0; i < (numbers.length - 1); i++ ) { first = numbers[i]; second = numbers[i + 1]; if ( missingNumber == null && !second.divide( first ).equals( gap ) ) { missingNumber = first.multiply( gap ); } else if ( !second.divide( first ).equals( gap ) && missingNumber != null ) { return null; } } return missingNumber; } catch ( Exception e ) { return null; } }  static Number testForPattern(Collection<NumberRestriction> restrictions); static final int MIN_NUMBER_OF_RESTRICTIONS; }
@Test public void testFindMultiplicationPattern() { assertTrue(FindMissingNumber.findMultiplicationPattern( new BigDecimal[] { BigDecimal.valueOf(2), BigDecimal.valueOf(8), BigDecimal.valueOf(16), BigDecimal.valueOf(32), BigDecimal.valueOf(64) }) .doubleValue() == 4); assertTrue(FindMissingNumber.findMultiplicationPattern( new BigDecimal[] { BigDecimal.valueOf(78), BigDecimal.valueOf(1326), BigDecimal.valueOf(22542), BigDecimal.valueOf(6514638) }).doubleValue() == 383214); assertTrue(FindMissingNumber.findMultiplicationPattern( new BigDecimal[] { BigDecimal.valueOf(1333), BigDecimal.valueOf(1639.59), BigDecimal.valueOf(2480.535711), BigDecimal.valueOf(3051.05892453) }).doubleValue() == 2016.6957); assertTrue(FindMissingNumber.findMultiplicationPattern( new BigDecimal[] { BigDecimal.valueOf(256), BigDecimal.valueOf(64), BigDecimal.valueOf(32), BigDecimal.valueOf(16), BigDecimal.valueOf(8), BigDecimal.valueOf(4), BigDecimal.valueOf(2) }) .doubleValue() == 128); assertTrue(FindMissingNumber.findMultiplicationPattern( new BigDecimal[] { BigDecimal.valueOf(10000), BigDecimal.valueOf(1000), BigDecimal.valueOf(100), BigDecimal.valueOf(10), BigDecimal.valueOf(0.1), BigDecimal.valueOf(0.01) }).doubleValue() == 1); assertTrue(FindMissingNumber.findMultiplicationPattern(new BigDecimal[] { BigDecimal.valueOf(111.2), BigDecimal.valueOf(3323), BigDecimal.valueOf(234.434), BigDecimal.valueOf(44343), BigDecimal.valueOf(434) }) == null); assertTrue(FindMissingNumber.findMultiplicationPattern(new BigDecimal[] { BigDecimal.valueOf(1), BigDecimal.valueOf(2), BigDecimal.valueOf(3), BigDecimal.valueOf(4), BigDecimal.valueOf(5), BigDecimal.valueOf(6), BigDecimal.valueOf(7), BigDecimal.valueOf(5), BigDecimal.valueOf(4), BigDecimal.valueOf(3), BigDecimal.valueOf(2), BigDecimal.valueOf(1), BigDecimal.valueOf(1), BigDecimal.valueOf(1) }) == null); }