Missing Numbers CodeChef Solution

Problem -Missing Numbers CodeChef Solution

This website is dedicated for CodeChef solution where we will publish right solution of all your favourite CodeChef problems along with detailed explanatory of different competitive programming concepts and languages.

Missing Numbers CodeChef Solution in C++17

#include <bits/stdc++.h>

using namespace std;

int main() {
    int t;
    int a[4];
    cin >> t;
    while (t--) {
        cin >> a[0] >> a[1] >> a[2] >> a[3];
        sort(a, a + 4);
        int m = -1, n = -1;
        do {
            int x, y, z, w;
            x = a[0]; 
            y = a[1]; 
            z = a[2]; 
            w = a[3]; 

            m = (x + y) / 2;
            n = abs(x - y) / 2;

            if (m > 0 && n > 0 && m <= 1e4 && n <=1e4) {
                if (m*n ==z && m/n==w) {
                    break;
                }
                else {
                    m = -1;
                    n = -1;
                }
            }
            else {
                m = -1;
                n = -1;
            }

        } while (
            next_permutation(a, a + 4)
            );
        cout << m << " " << n << endl;
    }
    return 0;
}

Missing Numbers CodeChef Solution in C++14

#include <bits/stdc++.h>
#define fs first
#define sn second
#define pb push_back

using namespace std;
using uint = unsigned int;
using ll = long long;
using ull = unsigned long long;
template <typename T>
using vec = vector<T>;
using str = string;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int t;
    cin >> t;
    while (t--) {
        vec<int> v(4);
        cin >> v[0] >> v[1] >> v[2] >> v[3];
        sort(v.begin(), v.end());
        bool f = false;
        int res1, res2;
        do {
            if (abs(v[0]) % 2 != abs(v[1]) % 2) continue;
            if (v[0] == v[1]) continue;
            int a = (v[0] + v[1]) / 2;
            int b = (v[0] - v[1]) / 2;
            if (a < 1 || b < 1 || a > 10000 || b > 10000) continue;
            if (a * b != v[2] || (a / b) != v[3]) continue;
            f = true;
            res1 = a;
            res2 = b;
            break;
        } while (next_permutation(v.begin(), v.end()));
        if (f) cout << res1 << ' ' << res2 << '\n';
        else cout << "-1 -1\n";
    }
    
    return 0;
}

Missing Numbers CodeChef Solution in PYTH 3

from itertools import permutations
t = int(input())
for _ in range(t):
    l = [int(x) for x in input().split()]
    flag = True
    for i in permutations(list(l)):
        A,B,C,D = i[0],i[1],i[2],i[3]
        a = (A+B)//2
        b = (A-B)//2
        if 1<=a<=10000 and 1<=b<=10000:
            if (a+b==A and a-b==B and a*b==C and b!=0 and a//b==D):
                print(a,b)
                flag = False
                break
    if flag:
        print("-1 -1")

Missing Numbers CodeChef Solution in C

#include <stdio.h>

int main(void) {
    int i1,n1;
    scanf("%d",&n1);
    for(i1=0;i1<n1;i1++)
    {
        int a[4],j;
        for(j=0;j<4;j++)
        	scanf("%d",&a[j]);
			
    int i,temp;
	for(i=0;i<3;i++)
	{
		for(j=0;j<3-i;j++)
		{
			if(a[j]>a[j+1])
			{
				temp=a[j];
				a[j]=a[j+1];
				a[j+1]=temp;
		    }
		}
						
    }
  		//case 1
    
        int A,B=0;
        A=(a[1]+a[2])/2;
        B=a[2]-A;
        if(B>0 && A>0 && A<10001 && B<10001)
        if(A*B==a[3] && A/B==a[0] )
        {
        	printf("%d %d\n",A,B);
        	continue;
    	}
        //case 2		
        A=(a[0]+a[2])/2;
        B=a[2]-A;
        if(B>0 && A>0 && A<10001 && B<10001)
        if(A*B==a[3] && A/B==a[1])
        {
       		printf("%d %d\n",A,B=a[2]-A);
       		continue;
		}
        
       // case 3
        A=(a[1]+a[3])/2;
        B=a[3]-A;
        if(B>0 && A>0 && A<10001 && B<10001)
        if(A*B==a[2] && A/B==a[0])
        {
        	printf("%d %d\n",A,B=a[3]-A);
        	continue;
    	}
        
        //case 4
        A=(a[0]+a[3])/2;
        B=a[3]-A;
        if(B>0 && A>0 && A<10001 && B<10001)
        if(A*B==a[2]&& A/B==a[1])
        {
        	printf("%d %d\n",A,B=a[3]-A);
        	continue;
		}
        printf("-1 -1\n");
        
    }
}

Missing Numbers CodeChef Solution in JAVA

/* package codechef; // don't place package name! */

import static java.util.Arrays.asList;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

/**
 * Missing Numbers
 * @see <a href="https://www.codechef.com/MARCH222C/problems/MISS_NUM">https://www.codechef.com/MARCH222C/problems/MISS_NUM</a>
 */
class MissingNumbers {

    private final InputStream in;
    private final PrintStream out;
    
    public MissingNumbers(
            final Boolean sample, final InputStream in, final PrintStream out) {
        this.in = in;
        this.out = out;
    }
    
    private void handleTestCase(final Integer i, final FastScanner sc) {
        final long[] a = sc.nextLongArray(4);
        Arrays.sort(a);
        String ans = "-1 -1";
        outer:
        for (int j = 0; j < 4; j++) {
            for (int k = j + 1; k < 4; k++) {
                final long xx = a[j] + a[k];
                if (xx % 2 != 0) {
                    continue;
                }
                final long x = xx / 2;
                final long y = Math.max(a[j], a[k]) - x;
                if (!(1 <= x && x <= 10_000 && 1 <= y && y <= 10_000)) {
                    continue;
                }
                if (y != 0) {
                    final long[] a1 = { x + y, x * y, x - y, x / y };
                    Arrays.sort(a1);
                    if (Arrays.equals(a, a1)) {
                        ans = String.format("%d %d", x, y);
                        break outer;
                    }
                }
                if (x != 0) {
                    final long[] a2 = { x + y, x * y, y - x, y / x };
                    Arrays.sort(a2);
                    if (Arrays.equals(a, a2)) {
                        ans = String.format("%d %d", y, x);
                        break outer;
                    }
                }
            }
        }
        this.out.println(ans);
    }
    
    public void solve() {
        try (final FastScanner sc = new FastScanner(this.in)) {
            final int numberOfTestCases = sc.nextInt();
            for (int i = 0; i < numberOfTestCases; i++) {
                handleTestCase(i, sc);
            }
        }
    }

    public static void main(final String[] args) throws IOException, URISyntaxException {
        final boolean sample = isSample();
        final InputStream is;
        final PrintStream out;
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        long timerStart = 0;
        if (sample) {
            is = MissingNumbers.class.getResourceAsStream("sample.in");
            out = new PrintStream(baos, true);
            timerStart = System.nanoTime();
        } else {
            is = System.in;
            out = System.out;
        }
        
        new MissingNumbers(sample, is, out).solve();
        
        out.flush();
        if (sample) {
            final long timeSpent = (System.nanoTime() - timerStart) / 1_000;
            final double time;
            final String unit;
            if (timeSpent < 1_000) {
                time = timeSpent;
                unit = "µs";
            } else if (timeSpent < 1_000_000) {
                time = timeSpent / 1_000.0;
                unit = "ms";
            } else {
                time = timeSpent / 1_000_000.0;
                unit = "s";
            }
            final Path path
                    = Paths.get(MissingNumbers.class.getResource("sample.out").toURI());
            final List<String> expected = Files.readAllLines(path);
            final List<String> actual = asList(baos.toString().split("\\r?\\n"));
            if (!expected.equals(actual)) {
                throw new AssertionError(String.format(
                        "Expected %s, got %s", expected, actual));
            }
            actual.forEach(System.out::println);
            System.out.println(String.format("took: %.3f %s", time, unit));
        }
    }
    
    private static boolean isSample() {
        try {
            return "sample".equals(System.getProperty("codechef"));
        } catch (final SecurityException e) {
            return false;
        }
    }
    
    private static final class FastScanner implements Closeable {
        private final BufferedReader br;
        private StringTokenizer st;
        
        public FastScanner(final InputStream in) {
            this.br = new BufferedReader(new InputStreamReader(in));
            st = new StringTokenizer("");
        }
        
        public String next() {
            while (!st.hasMoreTokens()) {
                try {
                    st = new StringTokenizer(br.readLine());
                } catch (final IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return st.nextToken();
        }
    
        public int nextInt() {
            return Integer.parseInt(next());
        }

        public long nextLong() {
            return Long.parseLong(next());
        }
        
        public long[] nextLongArray(final int n) {
            final long[] a = new long[n];
            for (int i = 0; i < n; i++) {
                a[i] = nextLong();
            }
            return a;
        }

        @Override
        public void close() {
            try {
                this.br.close();
            } catch (final IOException e) {
                // ignore
            }
        }
    }
}

Missing Numbers CodeChef Solution in PYPY 3

t=int(input())
for i in range(t):
    d=0
    v=0
    a=[]
    l=list(map(int,input().split()))
    for j in l:
        a.append(j)
    a.sort()
    for j in range(len(l)):
        for k in range(len(l)):
            if(j!=k):
                c=(l[j]+l[k])%2
                if(c==0):
                    # print(l[i],l[k],"entered")
                    c=(l[j]+l[k])//2
                    co=l[j]-c
                    if(co!=0):
                        ad=c+co
                        su=c-co
                        mu=c*co
                        di=c//co
                        f=[ad,su,mu,di]
                        f.sort()
                        if(a==f):
                            d=1
                            break
                        else:
                            su=co-c
                            di=co//c
                            f=[ad,su,mu,di]
                            f.sort()
                            if(a==f):
                                v=1
                                break
        if(d==1)or(v==1):
            break
                    
    if(c>=1 and c<=10**4)and(co>=1 and co<=10**4):               
        if(d==1):
            print(c,co)
        elif(v==1):
            print(co,c)
        else:
            print(-1,-1)
    else:
        print(-1,-1)
            

Missing Numbers CodeChef Solution in PYTH

t = int(raw_input())
for i in range(t):
	st = raw_input().split()
	A = []
	for x in st:
		A.append(int(x))
	# endfor x
	A.sort()
	L = []
	for p in range(3):
		for q in range(p+1,4):
			L.append([A[p],A[q]])
			L.append([A[q],A[p]])
		# endfor q
	# endfor p
	found = False
	k = 0
	a = -1
	b = -1
	while (not found) and (k < 12):
		p = L[k][0]
		q = L[k][1]
		if (p > 0) and (q > 0):
			n = p*p-4*q
			if n >= 0:
				r = int(n**0.5)
				if r*r == n:
					x = p+r
					if (x%2 == 0) and (x <= 20000):
						x = x/2
						y = (p-r)/2
						B = [x+y,x-y,x*y,x/y]
						B.sort()
						if A == B:
							a = x
							b = y
							found = True
						else:
							B = [x+y,y-x,x*y,y/x]
							B.sort()
							if A == B:
								a = y
								b = x
								found = True
							# endif
						# endif
					# endif
				# endif
			# endif
		# endif
		k += 1
	# endwhile
	print a, b
# endfor i

Missing Numbers CodeChef Solution in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

public class Test
{
    public class Miss_Num
    {
        public static List<long[]> permutations = new List<long[]>();

        private static void permute(long[] arr, int l, int r)
        {
            if (l == r)
            {
                permutations.Add(arr);
                //Console.WriteLine(str);
            }
            else
            {
                for (int i = l; i <= r; i++)
                {
                    arr = swap(arr, l, i);
                    permute(arr, l + 1, r);
                    arr = swap(arr, l, i);
                }
            }
        }

        public static long[] swap(long[] a, int i, int j)
        {
            long temp;
            long[] newArray = (long[])a.Clone();
            temp = newArray[i];
            newArray[i] = newArray[j];
            newArray[j] = temp;
            return newArray;
        }

        public static long[] Find_Miss_Num(long[] abcd)
        {
            //long[] abcd = Array.ConvertAll(Console.ReadLine().Split(), long.Parse);
            long a = -1, b = -1;
            permutations.Clear();
            permute(abcd, 0, abcd.Length - 1);

            foreach (var item in permutations)
            {
                long sum = item[0];
                long diff = item[1];
                long prod = item[2];
                long quot = item[3];

                //Console.WriteLine("sum={0}  dif={1}  prod={2}  quot={3}", sum, diff, prod, quot);

                double testa = (double)(sum + diff) / 2;
                double testb = (double)(sum - diff) / 2;

                if (testa % 1 == 0 && testb % 1 == 0)
                {
                    if (testa < 1 || testa > 10000 || testb < 1 || testb > 10000)
                    {
                        continue;
                    }

                    if (testa * testb == prod)
                    {
                        if (testb != 0)
                        {
                            if ((long)testa / (long)testb == quot)
                            {
                                a = (long)testa;
                                b = (long)testb;
                                break;
                            }
                        }
                    }
                }

            }

            return new long[] { a, b };
        }

    }
    
	public static void Main()
	{
	    int T = int.Parse(Console.ReadLine());
        for (int t = 0; t < T; t++)
        {
            string[] abcdString = Console.ReadLine().Split();
            long[] abcd = Array.ConvertAll(abcdString, long.Parse);
            long[] abRes = Miss_Num.Find_Miss_Num(abcd);
            
            Console.WriteLine(abRes[0] + " " + abRes[1]);
        }
	}
}

Missing Numbers CodeChef Solution in GO

package main

import (
	"bufio"
	"bytes"
	"fmt"
	"os"
)

func main() {
	reader := bufio.NewReader(os.Stdin)
	tc := readNum(reader)
	var buf bytes.Buffer

	for tc > 0 {
		tc--
		X := readNNums(reader, 4)
		res := solve(X)
		buf.WriteString(fmt.Sprintf("%d %d\n", res[0], res[1]))
	}
	fmt.Print(buf.String())
}

func readInt(bytes []byte, from int, val *int) int {
	i := from
	sign := 1
	if bytes[i] == '-' {
		sign = -1
		i++
	}
	tmp := 0
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + int(bytes[i]-'0')
		i++
	}
	*val = tmp * sign
	return i
}

func readNum(reader *bufio.Reader) (a int) {
	bs, _ := reader.ReadBytes('\n')
	readInt(bs, 0, &a)
	return
}

func readTwoNums(reader *bufio.Reader) (a int, b int) {
	res := readNNums(reader, 2)
	a, b = res[0], res[1]
	return
}

func readThreeNums(reader *bufio.Reader) (a int, b int, c int) {
	res := readNNums(reader, 3)
	a, b, c = res[0], res[1], res[2]
	return
}

func readNNums(reader *bufio.Reader, n int) []int {
	res := make([]int, n)
	x := 0
	bs, _ := reader.ReadBytes('\n')
	for i := 0; i < n; i++ {
		for x < len(bs) && (bs[x] < '0' || bs[x] > '9') && bs[x] != '-' {
			x++
		}
		x = readInt(bs, x, &res[i])
	}
	return res
}

func readUint64(bytes []byte, from int, val *uint64) int {
	i := from

	var tmp uint64
	for i < len(bytes) && bytes[i] >= '0' && bytes[i] <= '9' {
		tmp = tmp*10 + uint64(bytes[i]-'0')
		i++
	}
	*val = tmp

	return i
}

func solve(X []int) []int {
	// a + b, a - b, a * b, a / b
	// ops := []int{0, 1, 2, 3}

	check := func(i, j int) []int {
		// x is for addition, y is for substraction
		tmp := X[i] + X[j]
		if tmp%2 == 1 {
			return nil
		}
		a := tmp / 2
		b := X[i] - a
		if a <= 0 || a > 10000 || b <= 0 || b > 10000 {
			return nil
		}

		for l := 0; l < 4; l++ {
			if l == i || l == j {
				continue
			}
			if a*b == X[l] {
				k := 6 - i - j - l
				if a/b == X[k] {
					return []int{a, b}
				}
			}
		}

		return nil
	}

	for x := 0; x < 4; x++ {
		for y := 0; y < 4; y++ {
			if x == y {
				continue
			}
			res := check(x, y)
			if len(res) > 0 {
				return res
			}
		}
	}
	return []int{-1, -1}
}
Missing Numbers CodeChef Solution Review:

In our experience, we suggest you solve this Missing Numbers CodeChef Solution and gain some new skills from Professionals completely free and we assure you will be worth it.

If you are stuck anywhere between any coding problem, just visit Queslers to get the Missing Numbers CodeChef Solution.

Find on CodeChef

Conclusion:

I hope this Missing Numbers CodeChef Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.

This Problem is intended for audiences of all experiences who are interested in learning about Programming Language in a business context; there are no prerequisites.

Keep Learning!

More Coding Solutions >>

Cognitive Class Answer

CodeChef Solution

Microsoft Learn

Leave a Reply

Your email address will not be published. Required fields are marked *