You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言如何获取连续三个质数并验证首尾平均值等于中间值

实现思路
  • 维护3个变量缓存最近找到的3个连续质数,按查找顺序依次命名为first、second、third,初始值统一设为0
  • 每次在区间内找到新质数时,执行滑动更新逻辑:first = second,second = third,third = 新找到的质数
  • 每次更新完三个变量后,判断三个值是否都不为0(即已经收集到至少3个质数),如果满足条件直接做校验:由于三个质数是按从小到大顺序找到的,first天然是最小值、third天然是最大值,直接判断(first + third) == 2 * second即可,用乘法判断可避免整数除法的精度问题
完整修改后的代码
#include <stdio.h>
#include <math.h>

int main()
{
    int start = 0, end = 0, t = 2, flag = 0;
    // 存储连续三个质数的变量
    int first = 0, second = 0, third = 0;
    scanf("%d%d", &start, &end);
    for(; start <= end; start++){
        // 质数判断逻辑,终止条件改用sqrt可大幅优化遍历效率
        while(t <= sqrt(start)){
            if(start % t == 0){
                flag = 1;
                break;
            }
            t++;
        }
        if(flag == 0){
            // 滑动更新三个连续质数
            first = second;
            second = third;
            third = start;
            // 凑齐三个后执行校验逻辑
            if(first && second && third){
                if(first + third == 2 * second){
                    // 此处可替换为你需要的业务逻辑
                    printf("符合条件的三元质数组:%d %d %d\n", first, second, third);
                }
            }
        }
        t = 2;
        flag = 0;
    }
    return 0;
}

说明:如果不需要优化质数判断效率,可以删除math.h头引用,将循环判断条件改回t <= start / 2即可,功能完全一致。

内容的提问来源于stack exchange,提问作者Changer game

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 17:06:02