Assuming, you have year a and year b, which are the range of years (they are included), how to properly count leap years in this range without using loops? (gregorian calendar)
I wrote this on C#, but i don't think that my code is great. I also used a global variable, but lol, i think there are a solution that is so much better and more elegant than this. I'm just a newbie, so sorry that i'm asking this dumb question. Also, i don't think you should use DateTime here and etc.
Here's my code:
class Program
{
public static int leap_years = 0;
static void Main()
{
do
{
int a, b;
leap_years = 0;
do Console.Write("Enter a: ");
while (!int.TryParse(Console.ReadLine(), out a) || a < 0);
do Console.Write("Enter b: ");
while (!int.TryParse(Console.ReadLine(), out b) || b < 0 || a == b || a >= b);
Console.WriteLine("Leap years: " + countLeapYears(a, b));
} while (Console.ReadKey().Key != ConsoleKey.Escape);
}
Where countLeapYears
is
static public int countLeapYears(int a, int b)
{
if (a > b)
return leap_years;
else
{
if (a % 4 == 0)
{
if (a % 100 == 0)
{
if (a % 400 == 0)
{
Console.WriteLine("Year {0} - leap year", a);
leap_years++;
a += 4;
countLeapYears(a, b);
}
else
{
Console.WriteLine("Year {0} - not a leap year", a);
a++;
countLeapYears(a, b);
}
}
else
{
Console.WriteLine("Year {0} - leap year", a);
leap_years++;
a += 4;
countLeapYears(a, b);
}
}
else
{
Console.WriteLine("Year {0} - not a leap year", a);
a++;
countLeapYears(a, b);
}
}
return leap_years;
}
}
Well, we don't have year
0
:1BC
is followed by1AD
which spoils the fun. However, if we can work withAD
(positive years) only, you can try something like this:Let's test it with respect to naive computation:
Outcome: