简体   繁体   中英

Divide even number until the result is an odd number

I'm trying to divide a number by 2 if it's even, until each operation returns an odd number, so for example, dividing 16 by 2 returns 8 which dividing by 2 returns 4 until it gets to 2.

I've tried using recursion but it's performing really badly so I wrote the code below instead...the problem is that it's only dividing one time:

public int InchFraction(int value)
{
    for (int i = 0; i < value; i++)
    {
        if (value % 2 == 0)
        {
            value = value / 2;
            return value;
        }
    }
    return value;
}

InchFraction(16) //it's returning 8

public int InchFraction(int value)
{
    while (value % 2 == 0) 
        value /= 2;
    return value;
}

or since you are trying to optimise, try this

private static int countDivOps = 0;
private static int countCalls = 0;
static ulong M2(ulong v, int p = 32)
{
  var d = 1UL << p;
  countCalls++;
  while (v % d == 0) 
  {
    v /= d;
    countDivOps++;
  }
  return d == 2 ? v : M2(v, p / 2);
}
static void Main(string[] args)
{
  var v = 0x1204000000000000ul;
  var rv = M2(v);
  Console.WriteLine($"{v} reduces to {rv}(0x{rv:X}) in {countCalls} calls after (2x) {countDivOps} division operations");

It's not pretty and I leave you to play with your debugger and see what it's doing but FWIW the output is...

1298162592589545472 (0x1204000000000000) reduces to 1153(0x481) in 6 calls after (2x) 3 division operations

Note that the cost of the code is not all about division operations and calls, this was just to illustrate how you might approach this sort of problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM