Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Find the greatest number that doesn't divide by 2, 3, 5 and 7 but smaller than 1000

Tags:

c#

  public void ListTheBiggestNumberNotDividedBy2357()
    {
        for (int i = 1; i < 1001; i++)
        {
            if (!(i % 2 == 0) && !(i % 2 == 0) && !(i % 5 == 0) && !(i % 7 == 0))
            {
                Console.WriteLine(i);
            }
        }
    }

How to display only the biggest number? I tried with Math.Max() but I guess that's not what I should write.

like image 622
Trishka1111 Avatar asked Dec 18 '22 13:12

Trishka1111


2 Answers

(Note that I have fixed your typo of !(i % 2 == 0) && !(i % 2 == 0), which should be !(i % 2 == 0) && !(i % 3 == 0).)

The slow way

Keep a currentBiggest and update it every time you find such a number:

public void ListTheBiggestNumberNotDividedBy2357()
{
    int currentBiggest = 0;
    for (int i = 1; i < 1001; i++)
    {
        if (!(i % 2 == 0) && !(i % 3 == 0) && !(i % 5 == 0) && !(i % 7 == 0))
        {
            currentBiggest = i;
        }
    }
    Console.WriteLine(currentBiggest);
}

The fast way

Start from 1000 and go down. Print the first number you find, and break;, which stops the loop.

public void ListTheBiggestNumberNotDividedBy2357()
{
    for (int i = 1000; i > 0; i--)
    {
        if (!(i % 2 == 0) && !(i % 3 == 0) && !(i % 5 == 0) && !(i % 7 == 0))
        {
            Console.WriteLine(i);
            break;
        }
    }
}
like image 154
Sweeper Avatar answered Dec 24 '22 00:12

Sweeper


You can try a simple Linq in order to query numbers in (1000..0] range:

  using System.Linq;

  ...

  // let's extact divisors: it's easy to make a mistake like in the code in the question:
  // !(i % 2 == 0) instead of !(i % 3 == 0)
  int[] divisors = new int[] { 2, 3, 5, 7 };

  int result = Enumerable
    .Range(0, 999) // 999 - smaller than 1000
    .Reverse()
    .First(item => divisors.All(d => item % d != 0));

  Console.WriteLine(result);

Outcome:

  997 
like image 34
Dmitry Bychenko Avatar answered Dec 24 '22 01:12

Dmitry Bychenko