Home > Software design >  Prime number between N and M
Prime number between N and M

Time:12-04

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

CodePudding user response:

This if statement

if (i * num1 == num1 && num1 / i == num1)
{//make sure it only prints prime numbers
    cout << num1 << endl;
    sum  = num1;
}

is always evaluated for any number when i is equal to 1.

So the code has a logical error.

At least there is no sense to start the for loop

for (int i = 1; i <= num1; i  )

with i equal to 1.

Pay attention to that prime numbers are defined for natural numbers that is for numbers of unsigned integer types.

I would write the function at least the following way

unsigned long long int sum_of_primes( unsigned int first, unsigned int last )
{
    unsigned long long int sum = 0;

    if (not ( last < first ))
    {
        do
        {
            bool prime = first % 2 == 0 ? first == 2 : first != 1;

            for (unsigned int i = 3; prime && i <= first / i; i  = 2)
            {
                prime = first % i != 0;
            }

            if (prime) sum  = first;
        } while (first   != last);
    }

    return sum;
}

For example if in main to write this statement

std::cout << "sum_of_primes(0, 10) = " << sum_of_primes( 0, 10 ) << '\n';

then its output will be

sum_of_primes(0, 10) = 17

Indeed in this range [0, 10] prime numbers are 2, 3, 5, 7 and their sum is equal to 17.

  • Related