Sunday 24 December 2017

Write a function named factorTwoCount that returns the number of times that 2 divides the argument.

For example, factorTwoCount(48) returns 4 because
48/2 = 24
24/2 = 12
12/2 = 6
6/2 = 3
2 does not divide 3 evenly.

Another example: factorTwoCount(27) returns 0 because 2 does not divide 27.

The function signature is

   int factorTwoCount(int n);

First Way:
public static int factorTwoCount(int n)
        {
            int count = 0;
            while (n > 1)
            {
                if (n % 2 == 0)
                {
                    n = n / 2;
                    count++;
                }
                else
                {
                    break;
                }
            }
            return count;
        }
       Second way :
       
public static int factorTwoCount(int n)
        {
            int count = 0;
            bool flag = false;
            double temp = n;
            do
            {
                temp = temp / 2;
                flag = (temp % 1 == 0);
                if (flag)
                {
                    count++;
                }
            } while (flag);
            return count;
        }

6 comments:

  1. the first code is not correct, it will not work for negative numbers.

    and second one will run forever if n = 0;

    ReplyDelete
  2. # this is a better code

    public static int factorTwo(int n){

    int count = 0;

    while(n % 2 ==0){
    count += 1;
    n /=2;


    }

    return count;
    }

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete

Powered by Blogger.

Followers

Translate

Currency Converter

Exchange Rate

Featured post

Interpolation in angular 5

When we want to communicate from component class to template ,we can use interpolation which use the { { expression }} to render the bound...

Popular Posts

My Facebook Page