0

find numbers in an input range that are evenly divisible by 3. Only =, ++, -- operators can be used.

I've tried to get the remainder using shift operators and other loops but I always require a -= or something similar.

        Console.Clear();
        int n,
            d,
            count = 1;

        // get the ending number
        n = getNumber();

        // get the divisor
        d = 3;// getDivisor();

        Console.WriteLine();
        Console.WriteLine(String.Format("Below are all the numbers that are evenly divisible by {0} from 1 up to {1}", d, n));
        Console.WriteLine();

        // loop through
        while (count <= n)
        {
            // if no remainder then write number
            if(count % d == 0)
                Console.Write(string.Format("{0} ", count));

            count++;
        }

        Console.WriteLine();
        Console.WriteLine();
        Console.Write("Press any key to try again. Press escape to cancel");

Expected results:

Enter the ending number: 15

Below are all the numbers that are evenly divisible by 3 from 1 up to 15

3, 6, 9, 12, 15

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
BPierce
  • 53
  • 5
  • Right now I'm using the % operator and I am unable to find a different solution. – BPierce Feb 03 '19 at 17:16
  • C lang\lang-agnostic similar question here https://stackoverflow.com/questions/11694546/divide-a-number-by-3-without-using-operators?rq=1 – Woldemar89 Feb 03 '19 at 17:38

2 Answers2

0

If the == operator is permitted for the assignment, you can have something like

int remainder = 0; // assumes we always count up from 1 to n, we will increment before test

Inside the loop replace the existing if with

remainder++;
if (remainder == 3) { 
     Console.Write(string.Format("{0} ", count));
     remainder = 0;
}

[EDIT: Typo in code corrected]

Andrew Lazarus
  • 18,205
  • 3
  • 35
  • 53
0

Think about the underlying maths:

2 x 3 = 3 + 3
3 x 3 = 3 + 3 + 3
4 * 3 = 3 + 3 + 3 + 3

...and so on.

Also, to be evenly divisible by 3 means that the number multiplying 3 must be even.. So...

public bool EvenlyDivisibleBy3(int aNumber)
{
    int even = 2;
    int currentMultiple = 0;
    while (currentMultiple < aNumber)
    {
        int xTimes = 0;
        for (int x = 1; x <= even; x++)
        {
            ((xTimes++)++)++; // add three to xTimes
        }
        currentMultiple = xTimes;
        (even++)++: // next even number
    }

    return currentMultiple == aNumber;
}
simon at rcl
  • 7,326
  • 1
  • 17
  • 24