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.
(Note that I have fixed your typo of !(i % 2 == 0) && !(i % 2 == 0)
, which should be !(i % 2 == 0) && !(i % 3 == 0)
.)
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);
}
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;
}
}
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With