Home > Mobile >  Method to "convert" odd numbers to even numbers using a specific sequence
Method to "convert" odd numbers to even numbers using a specific sequence

Time:12-30

I'm recreating an application that has been done in Visual Basic 6.0 in C#, the problem is that I don't have the source code, and there's a method that reads a text file that could contain even numbers or odd numbers.

If the input value is an even number, does nothing, but if the input value is an odd number, it does something that I can't understand, doing some tests I could find a sequence:

enter image description here

What formula should I use to do this?

CodePudding user response:

This produces the desired output:

for (int i = 1; i < 50; i  = 2) {
    Console.WriteLine($"{i} -> {(i   1) / 4 * 4}");
    if (i % 10 == 9) {
        Console.WriteLine();
    }
}

Explanation: We are using integer arithmetic, i.e., the result of the division is truncated. For i = 5 we get (5 1) / 4 = 1, i.e., trunc(1.5) = 1 then 1 * 4 = 4.

For i = 7: (7 1) / 4 = 2, then 2 * 4 = 8.

Whenever the last digit of i is 9 we append an empty line to create the groups of 5 lines. % is the modulo operator. It is complementary to the integer division and yields the remainder of the division, e.g., 6 % 4 = 2. We can reverse the integer division like this: 6 / 4 * 4 6 % 4 = 6.

CodePudding user response:

If you can accept an answer in F#

let f x = ((x   1) / 4) * 4

for x = 1 to 49 do
    if x % 2 <> 0 then
        let y = f x
        Console.WriteLine $"{x} -> {y}"
  • Related