ZJANS

d491. 我也愛偶數 (swap 版)

Easy Last Update: 2026/01/30
數學

給兩個數字 a, b
求 a ~ b 中所有的偶數的總和為多少


解法一

✅ 完整代碼

評分結果(參考) : AC (3ms, 344KB)

#include <bits/stdc++.h>
#define int long long
using namespace std;

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    
    int a, b;
    cin >> a >> b;
    
    
    if(a > b) swap(a, b);
    if(a&1 == 1) a++;
    if(b&1 == 1) b--;
    
    int ans = (a+b)*((b-a)/2+1)/2;
    cout << max(ans, 0LL);
    
    return 0;
}