Write an algorithm to check whether a number is a prime number. in addition, write a program to implement this algorithm.
Answers
Answered by
0
Method 1:
read the number n.
Check the divisibility of the number from 2 to n/2.
If number is divisible by any of the numbers above . It isn't prime
Else it is prime.
Method 2:
1)suppose the number is 141
2)find nearest square root to it. In this case it is sqrt(144)=12.
3) Now check the divisibility of the number by prime numbers from 2 to 12. Here check whether 141 is divisible by 2,3,5,7,11.
#include <stdio.h>
int main()
{ int n, i, flag = 0;
printf("Enter a positive integer: "); scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{ // condition for nonprime number
if(n%i==0)
{
flag=1; break;
}
} if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
read the number n.
Check the divisibility of the number from 2 to n/2.
If number is divisible by any of the numbers above . It isn't prime
Else it is prime.
Method 2:
1)suppose the number is 141
2)find nearest square root to it. In this case it is sqrt(144)=12.
3) Now check the divisibility of the number by prime numbers from 2 to 12. Here check whether 141 is divisible by 2,3,5,7,11.
#include <stdio.h>
int main()
{ int n, i, flag = 0;
printf("Enter a positive integer: "); scanf("%d",&n);
for(i=2; i<=n/2; ++i)
{ // condition for nonprime number
if(n%i==0)
{
flag=1; break;
}
} if (flag==0)
printf("%d is a prime number.",n);
else
printf("%d is not a prime number.",n);
return 0;
}
Similar questions
Social Sciences,
7 months ago
English,
7 months ago
Computer Science,
1 year ago
Biology,
1 year ago
Math,
1 year ago
Social Sciences,
1 year ago