Home > other >  Why isn't break good enough?
Why isn't break good enough?

Time:02-28

C

When I first ran this code with a different input value of 881, 643, 743, etc... which are all primes numbers, I got a result of "True" but when I input a higher number like 804047277, it came back as "True" when it should have been "False"

#include <iostream>

int main(){

    int num;

    std::cin >> num;

    for(int i = 2; i < num; i  ){
        if(num % i == 0){
            std::cout << "True" << std::endl;
            break;
        }
        else{
            std::cout << "False" << std::endl;
            break;
        }
    }
    return 0;
}

I corrected my code (The code below) and received the correct answer, which was "False"

#include <iostream>

int main(){

    int num;

    std::cin >> num;

    for(int i = 2; i < num; i  ){
        if(num % i == 0){
            std::cout << "True" << std::endl;
            break;
            return 0;
        }
        else{
            std::cout << "False" << std::endl;
            break;
        }
    }
    return 0;
}

Shouldn't the break in the if statement stop the loop overall? I am just trying to understand why the break wasn't good enough, and I had to return 0;

CodePudding user response:

I would correct your code like following (see description afterwards):

Try it online!

#include <iostream>

int main() {
    int num = 0;
    std::cin >> num;
    
    for (int i = 2; i < num;   i)
        if (num % i == 0) {
            std::cout << "True (Composite)" << std::endl;
            return 0;
        }

    std::cout << "False (Prime)" << std::endl;
    return 0;
}

Input:

804047277

Output:

True (Composite)

As it is easy to understand, your program is intended to check primality and compositness of a number.

Mistake in your program is that you show False (Prime) when division by a very first i gives non-zero remainder. Instead, to actually check primality, you need to divide by all possible i and only if ALL of them give non-zero, then number is prime. It means that you shouldn't break or show False on very first non-zero remainder.

If ANY of i gives zero remainder then given number by definition is composite. So unlike the Prime case, this Composite case should break (or return) on very first occurance of zero remainder.

In code above on very first zero remainder I finish program showing to console that number is composite (True).

And only if whole loop finishes (all possible divisors are tested) then I show False (that number is prime).

Regarding question if break; is enough to finish a loop, then Yes, after break loop finishes and you don't need to return 0; after break, this return statement never finishes.

Also it is well known fact that it is enough to check divisibility until divisor equal to Sqrt(num), which will be much faster. So your loop for (int i = 2; i < num; i) should become for (int i = 2; i * i <= num; i) which is square times faster.

  • Related