doweto 2022-09-14 16:25 采纳率: 17.6%
浏览 116
已结题

C语言求质数和各项累加值

希望出现的结果是:
输出两列,一列是质数,另一列是累加值。
如下:
2 2
3 5
5 10
7 17
9 26
……

img

  • 写回答

5条回答 默认 最新

  • _GX_ 2022-09-14 17:39
    关注
    #include <stdio.h>
    
    // Returns 1 if x is a prime, otherwise returns 0.
    int is_prime(unsigned int x) {
      if (x < 2)
        return 0;
      for (int i = 2; i * i <= x; i++) {
        if (x % i == 0)
          return 0;
      }
      return 1;
    }
    
    // Restores the last calculated prime and sum from EEPROM.
    void restore(unsigned int *A, unsigned int *sum) {
      // ...
    }
    
    // Saves the calculated prime and sum to EEPROM for resuming the calculation
    // later.
    void save(unsigned int A, unsigned int sum) {
      // ...
    }
    
    // Shows LED for the specified period in ms.
    void showLed(unsigned int ms) {
      // ...
    }
    
    int main() {
      unsigned int A = 0, sum = 0, n = 0, i = 0;
      restore(&A, &sum); // Restore the last A and sum from EEPROM
      while (++i > 0) {
        if (is_prime(i)) {
          A = i;
          if (sum + i < sum) {
            printf("overflow, stop\n");
            break;
          }
          sum += i;
          printf("%u %u\n", i, sum);
          if (++n % 10 == 0)
            showLed(2000); // Show LED for 2 seconds
          save(A, sum);    // Save current A and sum to EEPROM
        }
      }
      return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 9月20日
  • 已采纳回答 9月17日
  • 创建了问题 9月14日

悬赏问题

  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题
  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan