Reputation: 231
This is a program that checks whether the input number is a product of two prime numbers ('Y') or not ('N').
#include <stdio.h>
// the function checks if the number is prime
int is_prime(int z) {
int i;
for(i=2; i<z; i++){
if(z%i == 0){
return 0;
}
return 1;
}
}
/* the function checks if the given number is a
product of two prime numbers bigger than 2*/
int is_prime_product(int x) {
int j;
for(j=2; j<x; j++){
if(x%j == 0){
if(is_prime(x/j) && is_prime(j)){
return 1;
break;
}else return 0;
}
}
}
int main() {
int n=0;
int c;
do{
c=getchar();
if((c>='0') && (c<='9')){
n= n*10+(c-'0');
}
} while (('0'<=c) && (c<='9'));
if(is_prime_product(c)){
putchar('Y');
}else{
putchar('N');
}
return 0;
}
I don't know why this program always returns 'Y' even when it should return 'N'. I just don't see where the mistake is.
Upvotes: 0
Views: 93
Reputation: 9772
Partial answer: Better version of is_prime:
int is_prime(int z)
{
if(z <= 1) return 0;
if(z == 2) return 1;
int i;
for(i=3; i<sqrt(z); i+=2)
{
if(z%i == 0) return 0;
}
return 1;
}
After the test for 2 it is enough to test for odd factors up to the square root of your test number. (Also fixed the curly braces)
Cause of your error:
if(is_prime_product(n)) ...
tests the input number n
not the last character c
Some hints for better (more readable, more reliable, and so on) code:
These things make a difference!
Have a look:
bool is_prime(unsigned int number)
{
if(number <= 1) return false;
if(number == 2) return true;
for(unsigned int factor = 3; factor < sqrt(number); factor += 2)
{
if(number % factor == 0) return false;
}
return true;
}
Upvotes: 2
Reputation: 1227
Please cheak your is_prime()
function. The code return 1;
should be after the for
loop.You can try the following:
int is_prime (int z)
{
int i;
for (i = 2; i < z; i++)
{
if (z % i == 0)
{
return 0;
}
}
return 1;
}
and your function is_prime_product ()
should be written as follow:
int is_prime_product (int x)
{
int j;
for (j = 2; j < x; j++)
{
if (x%j==0&&is_prime (x / j) && is_prime (j))
{
return 1;
}
}
return 0;
}
also you should use if (is_prime_product (n))
instead of if (is_prime_product (c))
.
Upvotes: 1
Reputation: 900
I have modified some of your code from main function. Please try with below code once,
Instead of this main function code:
int main() {
int n=0;
int c;
do{
c=getchar();
if((c>='0') && (c<='9')){
n= n*10+(c-'0');
}
} while (('0'<=c) && (c<='9'));
if(is_prime_product(c)){
putchar('Y');
}else{
putchar('N');
}
return 0;
}
Use this code:
int main() {
int n=0;
int c;
scanf("%d",&c);
do{
if((c>='0') && (c<='9')){
n= n*10+(c-'0');
}
} while (('0'<=c) && (c<='9'));
if(is_prime_product(c)){
putchar('Y');
}else{
putchar('N');
}
return 0;
}
Upvotes: 0