The first thing to encounter is this problem, the number of a given two can be divisible by 2,3,5 at the same time, it can be found that if a number can be divisible by 2,3,5 at the same time, then it will certainly be divisible by 30. We can write a function to determine whether a number can be divisible by 30, and then iterate through the interval of a given two number to judge on a single basis.
Solution one bool isnums (int num) {if (num%30==0) return True;return false;} int calculateNums2 (int begin,int end) {int count=0;for (int i=begin;i<=end;i++) {if (Isnums (i)) count++;} return count;}
But the time complexity of this method is too high.
There is a very ingenious way, is directly to find the [0,begin-1] can be divisible by 30 number of numbers;
Then the number of numbers that can be divisible by 30 in [0,end] is calculated.
The two subtracts are the number of numbers that can be divisible by 30 between [Begin,end].
Solution two int calculateNums1 (int begin,int end) {int left= (begin-1)/30;int right=end/30;int result=right-left;return Result ;}
This is the solution to the constant time.
The number of leap years can also be solved by this method.
- Can be divisible by 4, but not divisible by 100.
- Can be divisible by 400.
So the number of leap years in [0,begin-1] can be solved as follows:
(begin-1)/4-(begin-1)/100+ (begin-1)/400, which is the number of multiples of 4 in [0,begin-1] minus the number of multiples of 100, plus the number of multiples of 400. This is something that needs to be well thought out. This can be solved within a constant time.
#include <iostream>using namespace Std;int leapyears (int begin,int end) {int begin4= (begin-1)/4;int begin100= ( begin-1)/100;int begin400= (begin-1)/400;int left=begin4-begin100+begin400;int END4=END/4; int End100=end/100;int end400=end/400;int right=end4-end100+end400;int result=right-left;return result;} int main () {cout<<leapyears (1950,2050) <<endl;return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Find the number of leap years between two year (s)