快速查找整数的倍数

Finding multiples of integers quickly

本文关键字:整数 查找      更新时间:2023-10-16

我用C++编写了这段特殊的代码,试图找出整数3&5低于1000,方法是使用while循环,然后将其存储在整数数组中。我还想打印出这些倍数中的每一个。但每次我调试这个程序时,它都会无休止地打印出"0"。我就是不明白。有人能解释一下如何更正这个代码,以及为什么会出现异常输出吗?

#include <iostream>
using namespace std;
int main()
{
   const int three_limit = 334;
   const int five_limit = 200;
   int threeArray[three_limit] = {0};
   int fiveArray[five_limit] = {0};
   int i = 1, j = 1;
   while (i < three_limit)
   {
      int multiples = 3*i;
      multiples = threeArray[i - 1];
      cout << threeArray[i - 1] << endl;
      i++;
   }
   while (j < five_limit)
   {
      int multiples = 5*i;
      multiples = fiveArray[j - 1];
      cout << fiveArray[j - 1] << endl;
      j++;
   }
   char response;
   cin >> response;
   return 0;
}

当数字包含3和5的倍数时,输出将重复,例如15、30。

有些建议使用乘法或mod(%),这很慢,但使用二进制数组有一个更快的解决方案,也可以帮助您避免重复问题。类似于:

int main() {
    bool nums[1001];
    for(int i = 1; i < 1001; ++i)
        nums[i] = 0;
    for(int i = 3; i < 1001; i += 3)
        nums[i] = 1;
    for(int i = 5; i < 1001; i += 5)
        nums[i] = 1;
    for(int i = 1; i < 1001; ++i)
        if(nums[i])
            cout << i << endl;
}

应该是

threeArray[i - 1] = multiples;

而不是

multiples = threeArray[i - 1];

请参阅以下代码,生成5 的倍数

#include<stdio.h>
int main(){
int max=1000;
int i=1,result=0;

while(result!=max && i!=200)
{
    result=5*i;                    // change the 5 by 3 for multiples of 3
    printf("n %d",result);
    i++;
}       
}

我猜这个

multiples = threeArray[i - 1];

应该是

threeArray[i - 1] = multiples;

请尝试再次调试它,并在执行此行时监视multiples

multiples = threeArray[i - 1]; 

您正在用数组的(空)内容覆盖本地int——您的赋值方式不对。

您永远不会修改数组中的值。应该是这样的:

while (i < three_limit)
   {
      int multiples = 3*i;
      threeArray[i-1] = multiples;
      cout << threeArray[i - 1] << endl;
      i++;
   }