Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Method to "convert" odd numbers to even numbers using a specific sequence

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

What formula should I use to do this?

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading