Same And
Source: codechef
Difficulty: 1677

Same And
You are given two non negative integers$N$and$M$$(N<M)$. A beautiful sequence is defined as a sequence$S = \{X_1, X_2, \dots, X_K\}$of distinct non-negative integers, each at most$M$, that satisfies the following properties:
For all$1 \leq i \leq K$, we have$0 \leq X_i \leq M$.
For all$1 \leq i < j \leq K$,$X_i \neq X_j$.
For all$1 \leq i < j \leq K$,$X_i \& X_j = N$, where$\&$denotes the bitwise AND operation.
The length$K$is greater than$1$.
Given two non-negative integers$N$and$M$($N < M$), your task is to print the longest beautiful sequence. If there are multiple sequences with the maximum possible length, you may output any one of them. If no beautiful sequence exists, output$-1$.
Input Format
The first line of input contains a single integer$T$the number of test cases.
The first and only line of each test case consists of two space-separated integers$N$and$M$.
Output Format
For each test case
If there's no beautiful$N$sequence print -1.
Otherwise output a single integer$K$--- the maximum length of such a sequence. On the next line, print any valid sequence of$K$numbers separated by spaces.
Constraints$1 \leq T \leq 10^4$$0 \leq N \lt M \leq 10^{18}$Sample 1:
Explanation:
For the first test casde one valid beautiful 3 sequence is "7 3". In this sequence, both 7 and 3 lie between 0 and 7, they are distinct, and the bitwise AND of 7 and 3 equals 3. It can be verified that no beautiful sequence with more than 2 elements exists for these values.
For the second test it can be showed that no beautiful sequence can be formed when n = 1 and m = 2. Hence, the correct output is -1.

Sample Input:
2
3 7
1 2

Sample Output:
2
7 3 
-1

C++ solution:
#include <bits/stdc++.h>

#define xx first
#define yy second

using namespace std;
long long int typedef li;

const int mod=1'000'000'007;
//const int mod=998244353;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);

    int t; cin>>t;
    while (t--)
    {
        li n,m; cin>>n>>m;
        vector<li> ans;
        ans.push_back(n);
        for (int i=0;i<60;i++)
        {
            li temp=n|(1ll<<i);
            if (temp==n) continue;
            if (temp<=m) ans.push_back(temp);
        }

        if ((int)ans.size()==1) cout<<-1<<"\n";
        else
        {
            cout<<(int)ans.size()<<"\n";
            for (auto it : ans) cout<<it<<" ";
            cout<<"\n";
        }
    }
}

Go solution:
package main

import (
    "bufio"
    "fmt"
    "os"
    "strconv"
    "strings"
)

func main() {
    scanner := bufio.NewScanner(os.Stdin)
    writer := bufio.NewWriter(os.Stdout)
    defer writer.Flush()

    // Read number of test cases
    scanner.Scan()
    T, _ := strconv.Atoi(strings.TrimSpace(scanner.Text()))

    for t := 0; t < T; t++ {
        scanner.Scan()
        parts := strings.Split(strings.TrimSpace(scanner.Text()), " ")
        // Read N and M as int64
        N, _ := strconv.ParseInt(parts[0], 10, 64)
        M, _ := strconv.ParseInt(parts[1], 10, 64)

        // Build the sequence by always including N
        seq := []int64{N}

        // For bit positions 0 to 60 (sufficient for M up to 1e18)
        for pos := 0; pos < 61; pos++ {
            // If the pos-th bit is not set in N
            if (N>>pos)&1 == 0 {
                candidate := N | (1 << pos)
                if candidate <= M {
                    seq = append(seq, candidate)
                }
            }
        }

        // The sequence is valid only if it contains at least 2 elements
        if len(seq) < 2 {
            fmt.Fprintln(writer, -1)
        } else {
            fmt.Fprintln(writer, len(seq))
            strSeq := make([]string, len(seq))
            for i, num := range seq {
                strSeq[i] = strconv.FormatInt(num, 10)
            }
            fmt.Fprintln(writer, strings.Join(strSeq, " "))
        }
    }
}

Java solution:
/**
 * @author Abhisek Singh (Zyroßeast)
 * 
 */

import java.io.DataInputStream;
import java.io.IOException;

public class Main {

   /**
    * Main logic for the program.
    * 
    * @param args Not Used anywhere
    * @throws IllegalArgumentException If any Error happens while processing data.
    * 
    */
    public static void main(String[] args) throws IllegalArgumentException {
        initializeIO();
        try {
            int __ = nextInt(), count, i;
            long n, m, res[] = new long[64];
  
            while(__ -- > 0) {
                n = nextLong();
                m = nextLong();
                for(i = 0, count = 1; i < 63; i++) {
                    var temp = 1L << i;
                    if((n & temp) == 0 && (n | temp) <= m) res[count++] = n | temp;
                }
                if(count == 1) outData.append(-1);
                else {
                    outData.append(count).append('\n').append(n);
                    for(i = 1; i < count; i++) outData.append(' ').append(res[i]);
                }
                
                outData.append('\n');
            }
        
        } catch(IllegalArgumentException iae) {
            close();
            throw iae;
        }
        
        close();
    }
    
    
    
    
    
    
    
    
    
    
   /* The methods below are used for low level IO operations
    that will be used in the program. */
     
   /** InputStream with implemented buffering for faster input */
    private static DataInputStream dis;
   /** Buffer for input */
    private static byte[] buffer;
   /** Variables for reading buffer */
    private static int bytesRead, bufferPos;
   /** Unsynchronized Mutable String to store Output */
    private static StringBuilder outData;
    
   /**
    * Initializes the IO objects.
    * To be called before using IO methods.
    * 
    */
    private static void initializeIO() {
        dis = new DataInputStream(System.in);
        buffer = new byte[1 << 16];
        read();
        
        outData = new StringBuilder();
    }
    
   /**
    * Closes IO objects after execution.
    * 
    */
    private static void close() {
        try {
            System.out.print(outData);
            dis.close();
        }
        catch(IOException e) {
        }
    }
    
   /** To store next byte in buffer for Operations. */
    private static byte c;
   /** To store if a integer type data is negative or not. */
    private static boolean neg;
    
   /**
    * @throws IllegalArgumentException If the next input data is not an integer type.
    * 
    * @return The next Integer data from the input data
    * 
    */
    private static int nextInt() throws IllegalArgumentException {
        skipWhiteSpace();
        int temp = 0;
        
        neg = (c == '-');
        if(neg) {
            read();
        }

        do {
            if(!isDigit()) {
                throw new IllegalArgumentException();
            }
            
            temp = temp * 10 + c - '0';
            read();
        } while(!(c == '\n' || c == ' ' || c == '\r') && (c != -1));
        
        return neg ? -temp : temp;
    }
    
   /**
    * @param n The size of the array.
    * @throws IllegalArgumentException If the next input data is not an integer type.
    * @return The Integer array with the specified number of elements.
    * 
    */
    private static int[] nextIntArr(int n) throws IllegalArgumentException {
        int[] arr = new int[n];
        for(int i = 0; i < n; i ++) arr[i] = nextInt();
        return arr;
    }
    
   /**
    * @throws IllegalArgumentException If the next input data is not an integer type.
    * 
    * @return The next Long data in the input data
    * 
    */
    private static long nextLong() throws IllegalArgumentException {
        skipWhiteSpace();
        long temp = 0;

        neg = (c == '-');
        if (neg) {
            read();
        }
        
        do {
            if(!isDigit()) {
                throw new IllegalArgumentException();
            }
            
            temp = temp * 10L + c - '0';
            read();
        } while(!(c == '\n' || c == ' ' || c == '\r') && (c != -1));

        return neg ? -temp : temp;
    }

   /**
    * @param n The size of the array.
    * @throws IllegalArgumentException If the next input data is not an long type.
    * @return The Long array with the specified number of elements.
    * 
    */
    private static long[] nextLongArr(int n) throws IllegalArgumentException {
        long[] arr = new long[n];
        for(int i = 0; i < n; i ++) arr[i] = nextLong();
        return arr;
    }
    
   /**
    * @throws IllegalArgumentException If the next input data is not float or integer.
    * 
    * @return The next Double data in the input stream.
    * 
    */
    private static double nextDouble() {
        skipWhiteSpace();
        double temp = 0.0d;
        
        neg = (c == '-');
        if(neg) {
            read();
        }
        
        if(c != '.') {
            do {
                if(!isDigit()) {
                    throw new IllegalArgumentException();
                }
            
                temp = temp * 10.0d + c - '0';
                read();
            } while(c != '.' && !(c == '\n' || c == ' ' || c == '\r') && (c != -1));
        }
        
        if(c == '.') {
            double div = 1.0d;
            read();
            
            while(!(c == '\n' || c == ' ' || c == '\r') && (c != -1)) {
                if(!isDigit()) {
                    throw new IllegalArgumentException();
                }
            
                temp = temp * 10.0d + c - '0';
                div *= 10.0d;
                read();
            }
            
            temp /= div;
        }
        
        return neg ? -temp : temp;
    }

   /**
    * @param n The size of the array.
    * @throws IllegalArgumentException If the next input data is not an double type.
    * @return The Double array with the specified number of elements.
    * 
    */
    private static double[] nextDoubleArr(int n) throws IllegalArgumentException {
        double[] arr = new double[n];
        for(int i = 0; i < n; i ++) arr[i] = nextDouble();
        return arr;
    }
    
   /**
    * Checks if a byte is number or not.
    * 
    */
    private static boolean isDigit() {
        return (c >= '0' && c <= '9');
    }
  
   /** Stores the initial length of the given StringBuilder in the following functions. */
    private static int length;
   
   /**
    * Writes the remaining data from the current line from the input data in the given StringBuilder.
    * 
    * @param sb StringBuilder object in which the data will be stored.
    * @throws IllegalArgumentException If there is no byte left in input data.
    * @return The StringBuilder object after refilling it.
    *
    */
    private static StringBuilder getLine(StringBuilder sb) throws IllegalArgumentException {
        sb.setLength(0);
        
        while(c != -1) {
            if(c == '\n' || c == '\r') {
                break;
            }
            
            sb.append((char)c);
            read();
        }
        
        if(sb.length() == 0) {
            throw new IllegalArgumentException();
        }
        
        return sb;
    }
    
   /**
    * Writes the next line from the current line from the input data in the given StringBuilder.
    * 
    * @param sb StringBuilder object in which the data will be stored.
    * @return The StringBuilder object after refilling it.
    *
    */
    private static StringBuilder nextLine(StringBuilder sb) {
        skipLine(); getLine(sb);
        return sb;
    }
    
   /**
    * Appends the next word from the input data in the given StringBuilder
    * 
    * @param sb StringBuilder object in which the data will be stored.
    * @throws IllegalArgumentException If there is no byte left in input data.
    * @return The StringBuilder object after filling it.
    *
    */
    private static StringBuilder addNext(StringBuilder sb) throws IllegalArgumentException {
        skipWhiteSpace();
        length = sb.length();
        
        while(c != -1) {
            if(c == ' ' || c == '\n' || c == '\r') {
                break;
            }
            
            sb.append((char)c);
            read();
        }
        
        if(sb.length() == length) {
            throw new IllegalArgumentException();
        }
        
        return sb;
    }
    
   /**
    * Writes the next word from the input data in the given StringBuilder
    * 
    * @param sb StringBuilder object in which the data will be stored.
    * @return The StringBuilder object after refilling it.
    *
    */
    private static StringBuilder next(StringBuilder sb) {
        sb.setLength(0);
        addNext(sb);
        return sb;
    }
    
   /**
    * Skips any prevailing space or empty lines.
    * 
    */ 
    private static void skipWhiteSpace() {
        while((c == '\n' || c == ' ' || c == '\r') && (c != -1)) {
            read();
        }
    }
   
   /**
    * Skips any prevailing space.
    * 
    */
    private static void skipSpace() {
        while(c == ' ' && c != -1) {
            read();
        }
    }
     
   /**
    * Skips a line from the input stream.
    * 
    */
    private static void skipLine() {
        while(c != '\n' && c != '\r' && c != -1) {
            read();
        }
        
        while(c != -1 && (c == '\n' || c == '\r')) {
            read();
        }
    }
    
   /**
    * Skips a word from the input stream.
    * 
    */
    private static void skipWord() {
        while(c != '\n' && c != ' ' && c != '\r' && c != -1) {
            read();
        }
        
        read();
    }
    
   /**
    * Refills the buffer with new data.
    * 
    */
    private static void fillBuffer() throws IOException {
        bytesRead = dis.read(buffer, bufferPos = 0, buffer.length);
        
        if(bytesRead == -1) {
            buffer[0] = -1;
        }
    }
   
   /**
    * Reads the next byte from the input data and stores it in {@link c}
    * 
    */
    private static void read() {
        if(bufferPos >= bytesRead) {
            try {
                fillBuffer();
            }
            catch(IOException e) {
            }
        }
        
        c = buffer[bufferPos ++];
    }
}

JavaScript solution:
function solve(input) {
  // Split the input into lines and filter out empty lines.
  const lines = input.split("\n").filter(line => line.trim() !== "");
  let t = parseInt(lines[0]);
  let idx = 1;
  let output = [];

  while (t--) {
    // Read N and M as BigInts
    const [nStr, mStr] = lines[idx++].split(" ");
    let N = BigInt(nStr);
    let M = BigInt(mStr);
    let seq = [N]; // start with N in the sequence

    // Loop for i from 0 to 62 (63 iterations)
    for (let i = 0; i < 63; i++) {
      // Check if the i-th bit in N is set
      if ((N >> BigInt(i)) & 1n) continue;
      // Calculate candidate = N + (1 << i)
      let candidate = N + (1n << BigInt(i));
      if (candidate <= M) {
        seq.push(candidate);
      }
    }
    
    if (seq.length < 2) {
      output.push("-1");
    } else {
      output.push(seq.length.toString());
      // Convert each BigInt to a string before joining
      output.push(seq.map(x => x.toString()).join(" "));
    }
  }

  return output.join("\n");
}

// Node.js standard input handling:
if (typeof process !== 'undefined' && process.stdin) {
  process.stdin.resume();
  process.stdin.setEncoding("utf8");
  let inputData = "";
  process.stdin.on("data", function(chunk) {
    inputData += chunk;
  });
  process.stdin.on("end", function() {
    console.log(solve(inputData));
  });
} else {
  // If not running in Node (for example, in a browser), you can call solve directly:
  console.log(solve("1\n10 100\n"));
}

Python solution:
# cook your dish here
def find_seq(N, M):

    if N > M: return -1

    seq = [N] + [N | (1 << k) for k in range(64) if (N & (1 << k)) == 0 and (N | (1 << k)) <= M]
    return seq if len(seq) > 1 else -1

def main():
    import sys
    data = sys.stdin.read().split()
    T = int(data[0])
    idx = 1
    res = []
    for _ in range(T):
        N, M = int(data[idx]), int(data[idx + 1])
        idx += 2
        seq = find_seq(N, M)
        if seq == -1: res.append("-1")
        else: res.append(f"{len(seq)}\n{' '.join(map(str, seq))}")
    print("\n".join(res))

if __name__ == "__main__":
    main()

Ruby solution:
t = gets.to_i
t.times do
  n, m = gets.split.map(&:to_i)
  ans = [n]
  (0..63).each do |i|
    if (n & (1 << i)) == 0 && (n | (1 << i)) <= m
      ans << (n | (1 << i))
    end
  end
  if ans.size <= 1
    puts -1
  else
    puts ans.size
    puts ans.join(' ')
  end
end