-4

I wrote a small program to check if my number is a prime number or not. I think the code works fine, but I want the code to give me a single output: if it's a prime number or not.

I tried to find it on Google, but can't find an answer.

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main()
{
int z1,z_eingabe;
bool b1=true;

while(1){


printf("Zahl : ");
scanf("%d",&z_eingabe);

for(z1=2;z1<z_eingabe;z1++){
    if(z_eingabe%z1==0){
        printf("False %d\n",z1);
        b1=false;
        break;
    }
    if(b1==true){
        if(z_eingabe%z1!=0){
            printf("True\n");
            break;
        }
    }
}

}

    return 0;
}
zondo
  • 19,901
  • 8
  • 44
  • 83
MAXLooW
  • 17
  • 3

3 Answers3

1

use a boolean value and set it to true.

when you find a number that devides the input, put the value to false and break the loop.

at the end test your boolean: true -> printf("Ja\n"); false -> printf("Nein\n");

RomCoo
  • 1,868
  • 2
  • 23
  • 36
0

No, the code does not work fine.
Enter as input the numbers 9, 8, 9, and the program will report
Zahl : 9
True
Zahl : 8
False 2
Zahl : 9
False 3
Zahl :

To improve things, you should initialize the b1 boolean to true for each iteration of the while loop (and remove the while loop if you want the program to check only one number).

And then, do the check

if(z_eingabe%z1==0)

for all values of z1 before concluding that you have a prime number.

Here is the corrected code:

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

int main()
{
int z1,z_eingabe;
bool b1;

while(1){
b1=true;


printf("Zahl : ");
scanf("%d",&z_eingabe);

for(z1=2;z1<z_eingabe;z1++){
    if(z_eingabe%z1==0){
        printf("False %d\n",z1);
        b1=false;
        break;
     }
}
if(b1==true){
        printf("True\n");
}

}

    return 0;
}
0

If you want an algorithm, if you want to check a number is prime you have to divide it by prime numbers upto square root of that number and if its not divisible by them the number is prime.

For N , divide it by primes between 1 to sqrt(N) check if remainder for all those division is not 0 if anyone comes zero its not prime else its a prime