注册 登录
编程论坛 C++教室

帮忙检查一下我的代码吧!

夏浩晨 发布于 2025-12-06 15:39, 435 次点击
我正在做GESP5级的有趣的数字和,这是2025年9月的题目。可是我的代码老是出bug,我用平台的是洛谷(luogu)。你们可不可以看看为什么?
(屑Bro已经快崩了
我的代码:
#include<bits/stdc++.h>
using namespace std;

int a[24], l, r, sum;

bool check(int x){
    int x2 = x, cnt = 0;
    while(x2 > 0){
        cnt += x2 % 2;
        x2 /= 2;
    }
    return cnt % 2 == 1;
}

int main(){
    for(int i = 0; i < 6; i++){
        for(int j = 0; j < 24; j++){
            if(check(i * 24 + j)){
                a[i * 24 + j] = 1;
            }
        }
    }
    cin >> l;
    cin >> r;
    for(int i = l; i <= r; i++){
        if(a[i % 24]) sum += i;
    }
    cout << sum;
    return 0;
}
我的思路:
我发现满足“有趣”这个概念的数是有循环的。而check函数可以检测这个条件,所以我想按照循环来进行
具体症状:
部分答案错误,部分情况超时。
请各位大佬帮帮我!
3 回复
#2
夏浩晨2025-12-06 15:39
顺便一提,其实我是为了问问题才登陆的
#3
rjsp2025-12-07 16:33
题目要给出 https://www.

回正题,看你的代码,完全看不懂
从第一个for来看,应该定义 int a[6*24],从第二个for来看,就应该是 int a[24]
#4
rjsp2025-12-08 14:43
程序代码:
#include <iostream>
#include <bit>
using namespace std;

// [0,n) 内有趣元素累加和
unsigned foo( unsigned n )
{
    unsigned m = n/4;
    unsigned result = m*(4*m-1);
    for( unsigned i=4*m; i!=n; ++i )
        result += std::popcount(i)%2 * i;
    return result;
}

int main( void )
{
    unsigned l, r;
    cin >> l >> r;
    cout << foo(r+1)-foo(l);
}
1