Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::time::Instant;
- fn sunday_the_first_in_year(start_day : usize, leap_year : bool) -> usize {
- let mut current_day = start_day;
- let mut sundays = 0;
- for i in 1..12 {
- if current_day == 0 {
- sundays += 1;
- }
- let modulo = match i {
- 1 | 3 | 5 | 7 | 8 | 10 | 12 => {
- 31 % 7
- },
- 4 | 6 | 9 | 11 => {
- 30 % 7
- },
- 2 => {
- if leap_year {
- 29 % 7
- }else{
- 28 % 7
- }
- }
- _ => unreachable!()
- };
- current_day = (current_day + modulo) % 7;
- }
- if current_day == 0 {
- sundays += 1;
- }
- sundays
- }
- pub fn counting_sundays() -> usize {
- let mut days : [usize;14] = [0;14];
- for i in 0..7 {
- days[i] = sunday_the_first_in_year(i,false);
- days[i+7] = sunday_the_first_in_year(i,true);
- }
- let mut sundays = 0;
- let mut start_day = 2;
- for year in 1901..2001 {
- let is_leap_year = year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
- let index = if is_leap_year {
- start_day + 7
- }else {
- start_day
- };
- sundays += days[index];
- if is_leap_year {
- start_day = (start_day + 2) % 7;
- }else{
- start_day = (start_day + 1) % 7;
- }
- }
- sundays
- }
- pub fn main() {
- let now = Instant::now();
- let solution = counting_sundays();
- println!("{} in {:?}", solution, now.elapsed());
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement