Find the repeating and the missing number using two equations | Java implementation of the approach ; Function to print the required numbers ; Sum of first n natural numbers ; Sum of squares of first n natural numbers ; To store the sum and sum of squares of the array elements ; Driver code
public class GFG { static void findNumbers ( int arr [ ] , int n ) { int sumN = ( n * ( n + 1 ) ) / 2 ; int sumSqN = ( n * ( n + 1 ) * ( 2 * n + 1 ) ) / 6 ; int sum = 0 , sumSq = 0 , i ; for ( i = 0 ; i < n ; i ++ ) { sum += arr [ i ] ; sumSq += Math . pow ( arr [ i ] , 2 ) ; } int B = ( ( ( sumSq - sumSqN ) / ( sum - sumN ) ) + sumN - sum ) / 2 ; int A = sum - sumN + B ; System . out . println ( " A ▁ = ▁ " + A + " B = " + B); } public static void main ( String [ ] args ) { int arr [ ] = { 1 , 2 , 2 , 3 , 4 } ; int n = arr . length ; findNumbers ( arr , n ) ; } }