【问题标题】:Prime number between N and MN和M之间的质数
【发布时间】:2022-12-02 19:28:58
【问题描述】:

So I was trying to get the prime number between two numbers, it works fine but it also prints out odd numbers

int prime(int num1, int num2)
{
    int  sum{0};
    while (num1 <= num2)
    {
        for (int i = 1; i <= num1; i++)
        {
            if (num1 % i == 0) //remainder needs to be zero
            {
                if (num1 % 2 == 0) continue; //continue the loop if the number is even
                if (i * num1 == num1 && num1 / i == num1)
                {//make sure it only prints prime numbers
                    cout << num1 << endl;
                    sum += num1;
                }
            }
        }
        num1++;
    }
    return sum;
}

Console log

I tried to make a for loop that iterates between 1 and N and if the remainder is zero it also checks if the number is even.. if it is then it continues the loop. and then i checked for prime numbers.. if (i * num1 == num1 && num1 / i == num1) i expected it to print out only prime numbers and last the sum of them but it also counts odd numbers

  • There is a little more to primes : en.wikipedia.org/wiki/Sieve_of_Eratosthenes You can also calculate them once store them (in memory or disk) and then reuse the calculated results.
  • Find out the smallest set for which you get wrong values, then debug your code. For example by using a debugger to step through your code line by line while monitoring variables and their values.

标签: c++ function loops for-loop primes


【解决方案1】:
猜你喜欢
  • 2014-07-25
  • 2019-04-01
  • 2018-09-30
  • 1970-01-01
  • 2014-07-16
  • 2021-08-07
  • 2022-11-12
  • 2021-10-16
  • 1970-01-01
相关资源
最近更新 更多