How to write 6 different functions that accept 5 or 7 and return the other number, without using if,switch in C++

1 Answer

0 votes
#include <iostream>
#include <array>
#include <unordered_map>
#include <cmath>

/*
    Six different functions that accept 5 or 7
    and return the other number, without using if/switch.
*/

// 1. Arithmetic sum trick: 5 + 7 = 12
int flip_sum(int x) {
    return 12 - x;
}

// 2. Product trick: 5 * 7 = 35
int flip_product(int x) {
    return 35 / x;
}

// 3. XOR trick: 5 ^ 7 = 2
//    x ^ 2 flips 5 ↔ 7
int flip_xor(int x) {
    return x ^ 2;
}

// 4. Modulo-based trick using divisibility:
//    - x % 7 == 0 when x == 7
//    - x % 5 == 0 when x == 5
//    These expressions are 1 or 0 when used in arithmetic.
int flip_mod(int x) {
    return 5 * (x % 7 == 0) + 7 * (x % 5 == 0);
}

// 5. Absolute-value trick: |x - 12| flips 5 ↔ 7
int flip_abs(int x) {
    return std::abs(x - 12);
}

// 6. Array lookup using boolean indexing
int flip_array(int x) {
    static const std::array<int, 2> table = {7, 5};
    return table[x == 5];  // x==5 → 1 → 5; x==7 → 0 → 7
}

int main() {
    std::cout << "flip_sum(5) = " << flip_sum(5) << "\n";
    std::cout << "flip_sum(7) = " << flip_sum(7) << "\n\n";

    std::cout << "flip_product(5) = " << flip_product(5) << "\n";
    std::cout << "flip_product(7) = " << flip_product(7) << "\n\n";

    std::cout << "flip_xor(5) = " << flip_xor(5) << "\n";
    std::cout << "flip_xor(7) = " << flip_xor(7) << "\n\n";

    std::cout << "flip_mod(5) = " << flip_mod(5) << "\n";
    std::cout << "flip_mod(7) = " << flip_mod(7) << "\n\n";

    std::cout << "flip_abs(5) = " << flip_abs(5) << "\n";
    std::cout << "flip_abs(7) = " << flip_abs(7) << "\n\n";

    std::cout << "flip_array(5) = " << flip_array(5) << "\n";
    std::cout << "flip_array(7) = " << flip_array(7) << "\n";
}



/*
OUTPUT:

flip_sum(5) = 7
flip_sum(7) = 5

flip_product(5) = 7
flip_product(7) = 5

flip_xor(5) = 7
flip_xor(7) = 5

flip_mod(5) = 7
flip_mod(7) = 5

flip_abs(5) = 7
flip_abs(7) = 5

flip_array(5) = 5
flip_array(7) = 7

*/

 



answered Mar 31 by avibootz

Related questions

...