c - 500以下素数之和

标签 c

我编写了以下代码:

  1 #include<stdio.h>
  2 #include<stdbool.h>
  3
  4 bool c[500];
  5 void main()
  6 {
  7  int i,n=1,j;
  8  for (i=2; i<500; i++)
  9  {
 10         if (!c[i])
 11         {
 12                 printf("%d is the prime number %d\n", i,n);
 13                 n++;
 14                 j=2;
 15                 while (j*i<500)
 16                 {
 17                         c[j*i]=1;
 18                         j++;
 19                 }
 20         }
 21  }
 22 }

显示500以下的质数;现在,我怎样才能让程序在短短几行内显示所有这些数字的总和(所有 500 以下的质数)?谢谢你的帮助,我是 C 新手

最佳答案

  1. 首先,将变量 sum 设置为零。
  2. 然后,每次当前输出质数时,也将其添加到 sum 中。
  3. 然后,完成后输出sum
<小时/>

因此,假设您的代码可以正常工作,您需要更改上面的第 1 点:

int i,n=1,j;

进入:

int i,n=1,j,sum=0;
<小时/>

第 2 点涉及更改:

printf("%d is the prime number %d\n", i,n);

进入:

printf("%d is the prime number %d\n", i,n);
sum += i;
<小时/>

最后,第 3 点可以通过以下方式制定:

printf("Sum of all those primes is %d\n", sum);

在最后的右大括号之前。

<小时/>

对代码的更改(包括注释和更合适的变量名称以提高可读性)将类似于:

#include <stdio.h>
#include <stdbool.h>

// Find/sum all primes less than this number.

#define LIMIT 500

// Flag indicating a number is non-prime, initialised to zeros.

bool isComposite[LIMIT];

void main (void) {
    int num, mult;
    int count = 1, sum = 0;

    // Check every number for primeness.

    for (num = 2; num < LIMIT; num++) {
        // Ignore if composite.

        if (!isComposite[num]) {
            // Print prime, add to sum.

            printf ("%d is the prime number %d\n", num, count++);
            sum += num;

            // Mark all multiples of it as composite.

            for (mult = num * 2; mult < LIMIT; mult += num) {
                isComposite[mult] = 1;
            }
        }
    }

    // Now just output the sum.

    printf ("The sum of those primes is %d\n", sum);
}

如果是类作业,请勿抄袭,您可能会被发现。我添加它只是为了向您展示如果您遵循一些简单的规则(其中一些规则如下),代码的可读性会提高多少:

  • 大量使用注释,通常是描述您在做什么,而不是如何做。
  • 使用合适的变量名称。
  • 尽量避免使用 500 等“神奇”常量。
  • 在不影响可读性的情况下尽量减少垂直空间(通常最好在屏幕上看到尽可能多的代码)。

关于c - 500以下素数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27162419/

相关文章:

c - 为什么在引用 int 变量的大小时必须使用 %ld?

c - 我是否转换 malloc 的结果?

c - 使用 Windows Spooler API 以编程方式打印 PDF 文件

我根本找不到C内存泄漏

c++ - 查找表示为链表的 2 个数字之和的最佳方法

c - 循环变量显示垃圾值

java - 通过串行端口的 xml 消息传递

c - vim:C 将大括号缩进与 case 同级

c - GTK:获取窗口中鼠标单击的坐标

c - 覆盖 gcov 函数以获取已执行的代码行