-1

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

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
Zoon
  • 19
  • 1
  • 1
    There is a little more to primes : https://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. – Pepijn Kramer Dec 02 '22 at 10:54
  • Find out the smallest set for which you get wrong values, then [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your code. For example by using a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through your code line by line while monitoring variables and their values. – Some programmer dude Dec 02 '22 at 10:54
  • Welcome to Stack Overflow. Please read https://ericlippert.com/2014/03/05/how-to-debug-small-programs/ and try to think about the code carefully. What values of `i` do you expect will be used for the test `if (i * num1 == num1 && num1 / i == num1)`? In particular, do you think that the value `1` will be used? (Why or why not? Did you check?) Will that condition be met, if `i` is equal to `1`? Can `i` be equal to `1`? (Hint: what part of the code determines the values used for `i`?) **Should** `i` ever be equal to `1`? (Hint: do you try dividing by 1 when solving the problem by hand?) – Karl Knechtel Dec 02 '22 at 11:36
  • As written, a sub function `is_prime` would be useful (and testable independently). – Jarod42 Dec 02 '22 at 14:35
  • `if (i * num1 == num1 && num1 / i == num1)` is equivalent to `if (i == 1 || num1 == 0)`... – Jarod42 Dec 02 '22 at 14:37
  • `if (num1 % i == 0) //remainder needs to be zero` Not for prime numbers. – Jarod42 Dec 02 '22 at 14:38

1 Answers1

0

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.

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
  • Supposing that the `1` used in initializing the loop isn't a typo, it's a conceptual problem with the steps that need to be taken - in other words, a math or logic question, not a programming question. Either way, this does not make an on-topic question for Stack Overflow, and as such it should not be answered. (To the extent that the general question of "how do I find prime numbers using trial division" has value, questions like this one should instead be routed to a canonical, although they are probably still not good signposts.) – Karl Knechtel Dec 02 '22 at 11:39
  • @Karl Knechtel. Is this a opinion or can I read a technical rule somewhere? If there is such a technical rule, can you please kindly guide me to there? – A M Dec 02 '22 at 12:26
  • 1
    @AM With at least 3000 reputation, you can see the close reasons underneath the `Close` link on any question. The topicality requirements are described in [ask] and [answer] and https://stackoverflow.com/help/on-topic. If you are unsure about anything (or have a disagreement), you can ask on https://meta.stackoverflow.com (of course, look for existing discussion there, first, too - there is an entire category of FAQ questions there). – Karl Knechtel Dec 02 '22 at 12:33
  • 1
    I am very confident in my close vote and downvotes, but I will not discuss the matter here further. Please take it to Meta. (That said, labelling something "silly and wrong" is only condescension and rudeness, not an argument.) – Karl Knechtel Dec 02 '22 at 12:39
  • Can you explain bool prime = first % 2 == 0 ? first == 2 : first != 1; for (unsigned int i = 3; prime && i <= first / i; i += 2) { prime = first % i != 0; } Aswell as the if(not) part – Zoon Dec 03 '22 at 11:29