กำหนดค่าจำนวนเต็มบวก n งานคือสร้างจำนวนวันที่เกิน (odd days) จนถึงปีที่กำหนด n
ตัวอย่าง
Input: days = 500 Output: number of odd days are: 5 Input: days = 400 Output: number of odd days are: 0
วิธีคำนวณจำนวนวันที่เกินในปีที่กำหนด
สำหรับการคำนวณจำนวนวันที่เกิน สิ่งแรกที่ต้องตรวจสอบคือปีที่กำหนดเป็นปีอธิกสุรทินหรือไม่ เพราะถ้าเป็นปีอธิกสุรทิน จำนวนวันที่เกินจะเปลี่ยนไป หากปีหาร 100 หรือ 400 ลงตัวแต่ไม่หาร 4 ลงตัว ปีจะเป็นปีอธิกสุรทิน มิฉะนั้นจะเป็นปีปกติ ถ้าหารเศษของจำนวนวันทั้งหมดด้วย 7 (จำนวนวันในหนึ่งสัปดาห์) ปีปกติประกอบด้วย 1 วันที่เกิน และปีอธิกสุรทินประกอบด้วย 2 วันที่เกิน
วิธีการที่ใช้ในโปรแกรม −
- รับจำนวนวันเป็นอินพุต
- ตรวจสอบว่าปีเป็นปีอธิกสุรทินหรือปีปกติ
- คำนวณวันที่เกินโดยการหารจำนวนวันทั้งหมดด้วย modulus
- แสดงผลลัพธ์สุดท้ายเป็นจำนวนวันในปีจาก 1 ถึง n
อัลกอริทึม
Start
Step 1 → ประกาศฟังก์ชันคำนวณจำนวนวันที่เกินในปีที่กำหนด
int cal_odd(int days)
ประกาศ int cal_1 = days / 100
ประกาศ int cal_2 = days / 400
ประกาศ int check_leap = days >> 2
ประกาศ int temp = days - check_leap
IF (cal_1)
ตั้งค่า temp += cal_1
ตั้งค่า check_leap -= cal_1
End
IF (cal_2)
ตั้งค่า temp -= cal_2
ตั้งค่า check_leap += cal_2
End
ประกาศ int final_days = temp + check_leap * 2
ประกาศ int odd = final_days % 7
return odd
step 2 → ใน main()
ประกาศ int days = 500
เรียก cal_odd(days)
Stop
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
// คำนวณจำนวนวันที่เกินในปีที่กำหนด
int cal_odd(int days) {
int cal_1 = days / 100;
int cal_2 = days / 400;
int check_leap = days >> 2;
int temp = days - check_leap;
if (cal_1) {
temp += cal_1;
check_leap -= cal_1;
}
if (cal_2) {
temp -= cal_2;
check_leap += cal_2;
}
int final_days = temp + check_leap * 2;
int odd = final_days % 7;
return odd;
}
int main() {
int days = 500;
cout << "number of odd days are : " << cal_odd(days);
return 0;
}
ผลลัพธ์
number of odd days are : 5