首页 > 解决方案 > 打印出特定间隔之间的完美数字

问题描述

// starting, end,  number, sum of the divisor, delimiter 
int pocetok, kraj, broj,   zbir_na_deliteli=0, delitel=1;
printf("Vnesi go intervalot: ");  // Enter the interval
scanf("%d%d", &pocetok, &kraj);

for(broj=pocetok;broj<=kraj;broj++)
    for(;delitel<broj;delitel++){
        if(broj%delitel==0)
            zbir_na_deliteli+=delitel;
    }
    if(zbir_na_deliteli==broj)
        // The number %d is a perfect number
        printf("Brojot %d e sovrshen broj\n", broj);
    }

这是我写的程序。我实际上是在逐行将它与一个已解决的程序进行比较,该程序执行完全相同的操作,除了一个有效但这个无效。

有人可以向我解释我做错了什么吗?

标签: c

解决方案


有人可以向我解释我做错了什么吗?

计数器delitel需要在每个循环的 1 处重新启动

    // for(;delitel<broj;delitel++){
    for (int delitel = 1; delitel < broj; delitel++) {

每次循环总和zbir_na_deliteli需要重置为 0

  for (int broj = pocetok; broj <= kraj; broj++) {
    int zbir_na_deliteli = 0;

示例代码:

void Printing_out_the_perfect_numbers(int pocetok, int kraj) {
  for (int broj = pocetok; broj <= kraj; broj++) {
    int zbir_na_deliteli = 0;
    for (int delitel = 1; delitel < broj; delitel++) {
      if (broj % delitel == 0) {
        zbir_na_deliteli += delitel;
      }
    }
    if (zbir_na_deliteli == broj) {
      printf("Brojot %d e sovrshen broj\n", broj);
    }
  }
}

int main() {
  Printing_out_the_perfect_numbers(1, 10000);
}

输出

Brojot 6 e sovrshen broj
Brojot 28 e sovrshen broj
Brojot 496 e sovrshen broj
Brojot 8128 e sovrshen broj

更快的方法不会测试除法broj,而是测试 的平方根broj。与其直接计算平方根,不如跟踪商和余数。许多编译器会为商和余数(%/)提供一次计算,以免产生额外昂贵的除法。

void Printing_out_the_perfect_numbers(int pocetok, int kraj) {
  for (int broj = pocetok; broj <= kraj; broj++) {
    int zbir_na_deliteli = 0;
    int kvocient = broj;
    for (int delitel = 1; delitel < kvocient; delitel++) {
      if (broj % delitel == 0) {
        kvocient = broj / delitel;
        zbir_na_deliteli += delitel;
        if (kvocient > delitel) {
          if (delitel != 1) zbir_na_deliteli += kvocient;
        } else {
          break;
        }
      }
    }
    if (zbir_na_deliteli == broj) {
      printf("Brojot %d e sovrshen broj\n", broj);
    }
  }
}

完美数有害数


推荐阅读