0
I started programming recently and soon they gave me the problem of creating an algorithm to check whether a number is prime or not. As at the time I was still having some difficulty in looping repetitions, I created an if/Else-based algorithm to solve the problem:
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
int a;
scanf("%d",&a);
if(((((a % 2 == 0) and (a != 2))
or ((a % 3 == 0) and (a != 3)))
or (((a % 5 == 0) and (a != 5))
or ((a % 7 == 0) and (a != 7)))) )
{
}
else
{
printf("%d ", a);
}
return 0;
}
The algorithm even checks whether a number is prime or not, but when the factorization of a number is the multiplication of two prime numbers such as 169 (13*13) or 143 (11*13), the number also passes as prime. I used the Math. h library to compute the root of the number and exclude it when it is a square of a prime number:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
int a;
float c, b;
scanf("%d", &a);
c = a;
b = sqrt(c) ;
if (a == 1)
{
printf("o numero 1 nao eh primo");
}
if((((((a % 2 == 0) and (a != 2))
or ((a % 3 == 0) and (a != 3)))
or (((a % 5 == 0) and (a != 5)) or ((a % 7 == 0) and (a != 7)))) or floor(b) == b ))
{
printf("Nao eh primo\n\n\n");
}
else
{
printf("%d eh primo\n\n\n", a);
}
return 0;
}
But I haven’t been able to solve numbers that have the same case of 143, my doubt is as if I can verify if a number is prime or not without use loop loops. Thank you :)
Your program cannot and does not check if the number is prime. To have given the result you expected was mere coincidence. You only check if the number is multiple of 2, 3, 5 and 7 without being one of them. This is not checking if it is prime. The definition of being prime is that the number needs to be divisible only by 1 and by itself, so you will necessarily have to create a repeat loop to test all possible divisors.
– Woss
P/ do without ties, have a well "gambiarra alternative":
if (n == 2 || n == 3 || n == 5 || n == 7 || n == 11 ...)
(include all primes in that list, up to the highest possible value for aint
). But why do you want to do without ties, if with ties is much easier?– hkotsubo