I just want a 1 or 0 if it is prime or not. but I am getting multiple 0's and 1's. How can I solve this.
#include <stdio.h>
int num() {
int a, i;
printf("Enter a number:");
scanf("%d", &a);
for (i = 2; i < a; i ) {
if (a % i == 0)
printf("1");
else
printf("0");
}
}
int main() {
num();
return 0;
}
CodePudding user response:
Based on the naming used and specific combination of function use, I am almost certain OP's code is based off this which is my first google response to c check if number is prime
.
I challenged myself to "fix" it with least number of modification to the original code, here is the version that works the way OP expects. It is ugly but the point is to make it clear where it differs from his code.
OP seems to have mixed up the inner if statements with the outer if statements, and completely forgot about the counter. Also OP seems to have got confused in the function num, as it should either print 1 or 0 and be a void function, or return 1 or 0 and take a
as input to a function that returns int
eg int num(int a)
or void num()
, whereas OP ended up going halfway int num()
.
The working(if you can call it that, since fflush(stdout)
is not called after printf is called, so the program will not not show the question on mingw without winpty
) program would look like this:
#include <stdio.h>
void num() {
// a is the user input number
// c is the count
// i is the iterator
int a, i, c = 0;
printf("Enter a number: ");
scanf("%d", &a);
for (i = 2; i < a; i ) {
if (a % i == 0)
c;
}
if (c != 0)
printf("0");
else
printf("1");
}
int main() {
num();
return 0;
}
CodePudding user response:
The reason you get multiple 0
s and 1
s is you print them for every potential factor. You should instead test the factors to determine if none of the factors up to the square root of the number divide the number evenly, printing a 1
in this case and a 0
otherwise.
Function isprime
should take an int
argument and return 1
or 0
, the main()
function takes case of getting the number from the user and printing the result.
Here is a modified version:
#include <stdio.h>
int isprime(int a) {
int i;
if (a < 2)
return 0;
for (i = 2; a / i >= i; i ) {
if (a % i == 0)
return 0;
}
return 1;
}
int main() {
int a;
printf("Enter a number:");
if (scanf("%d", &a) == 1) {
printf("%d\n", isprime(a));
}
return 0;
}
Also note how the code is indented and uses spaces to improve readability. Learn how to do this for your next projects.