'How to print 7 when user input 3 without using any condition

So, here is a question when user input 3 than it prints the 7 as output and when user input 7 than it prints 3 as output, but without using any condition and loop.

here is what I done.But the problem is i'm using 2 numbers as input but i have to done it with one input.

void main() {
  print(mod(7, 3));
}

int mod(int num1, int num2) {
  //3*2 mod 7
  //7*2 mod 3
  int answer = (num1 * 2) % num2 + 1;
  return answer;
}

please help how to do this.You can use any language to solve this.



Solution 1:[1]

Let's look at the binary representation of 3 and 7 : 3 is 0...0011 and 7 is 0...0111, which means that the only bit that differs between 3 and 7 is the 3rd bit. Therefore, we can transform 3 into 7 and vice-versa simply by "flipping" that 3rd bit.

"Flipping a bit" can be done with an "exclusive-or" operation. Xor is a very useful operation (one of my favorite): one way to look at it is to consider that you have a data input and a control input, and if the control input is 0, then the data input is left unchanged, but if the control input is 1, then the data input is flipped (you can draw the truth table of Xor to convince yourself of that interpretation). Of course, it's only a way to consider the xor operation, but it's particularly useful in our case : we want to flip the 3rd bit, and leave all of the other bit unchanged.

C offers a "bitwise xor" operation ( A ^ B), which do a xor of each bit of A and B. Therefore, what we want is to have a number, that we will use as the control number, which 3rd bit is 1 and all other bits are 0: this number is 4.

Finally, we can have this function that converts 3 into 7 and vice-versa by simply applying a Xor with 4 to the input.

#include <stdio.h> 

int flip(int num1) {
    return num1 ^ 4;
}

void main() {
    printf("%d", flip(3)); 
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bromind