I used the following code and it showed numbers like 49 as prime and not composite. I am new to programming so please help me with the correct code.
#include <stdio.h>
int main()
{
int n;
int i;
scanf ("%d", &n);
for (i=2; i<n; i++)
{
if (n%i==0)
{
printf ("number is composite");
}
else
{
i=i+1;
}
}
printf("number is prime");
return 0;
}
You didn't stop the loop when you discovered that the number was composite, so composite numbers get both messages.
When i is not a factor of n you are adding 1 to i but then the for loop adds 1 again. This means that for every number that is not a factor of n you skip a number.
The printf("number is prime"); is not surrounded by any kind of if, so it will always be printed regardless of whether or not the number is actually prime. Unlike humans, computers won't think twice about printing conflicting information because computers are incapable of interpreting the actions we make them do.
You can optimize your code by checking less numbers. Only check up to the square root of the number.
This code is untested but should work. Note that this only eliminates the checking of factors above the square root, but not any multiples of previously checked factors (e.g. written like this, the program will check if the number is divisible by 2 but also by 4, 6, 8, 10, etc).
#include <stdio.h>
#include <math.h>
int main()
{
int n;
int i;
int isComposite = 0;
scanf ("%d", &n);
for (i = 2; i <= (int)sqrt((double)n); i++){
if (n % i == 0){
printf ("number is composite");
isComposite = 1;
break;
}
}
if (!isComposite){
printf("number is prime");
}
return 0;
}
You can modify your loop as follows -
if(n%2==0 && n!=2){ //if 2's multiple is entered no need of loop just check this
printf("number is composite");
return 2; // for sake I just returned 2
}
for (i=3; i<n;i=i+2)
{
if (n%i==0) // if this is true
{
printf ("number is composite"); // print this
return 1; // return from function no further iterations
}
}
In this way you stop loop as if condition is true and its code in its block us executed .
You should remove i=i+1 line, you increment i already in for (i=2; i<n; i++)
After that, you must put your conditions after the loop for prevent print result at every check.
#include <stdio.h>
int main()
{
int n;
int i;
scanf ("%d", &n);
for (i = 2; i<n; ++i)
{
if (n%i==0)
{
printf ("number is composite, divisible by %d\n", i);
break;
}
printf("i=%d\n", i);
}
if (n%i != 0)
printf("number is prime\n");
return 0;
}
Combining all suggestions and comments gives:
int q= (int) sqrt(n);
if (n%2==0)
{
printf ("number is composite"); // print this
return 1; // return from function no further iterations
}
for (i=3; i<=q; i += 2)
{
if (n%i==0) // if this is true
{
printf ("number is composite"); // print this
return 1; // return from function no further iterations
}
}
the reason you are getting 49 a s composite is because of this line:
else
{
i=i+1;
}
this causes you to skip odd numbers in your check, and 49 is 7*7, therefore the ouput yo get is that it is prime.
Another problem you have is that you do not stop the loop when you get a composite number, and at the end of it you will invoke this line of code regardless of what happens in the loop.
printf("number is prime");
here is a better practice:
create a function that will return 1 if it is prime, and 0 if it is not.
if you realize that it is a composite number, you should return immediately. if you get to the end of the loop, it is definatley a prime number.
also, you can run your loop to the square root of n to gain a smaller amount of iterations, and not until n.
good luck
int isPrime(int n)
{
int i;
for (i = 2; i < (int) sqrt(n) ; i++)
{
if (n % i == 0)
{
printf("number is composite");
return 0;
}
}
printf("number is prime");
return 1;
}
Here you are.
#include <stdio.h>
int main( void )
{
while ( 1 )
{
unsigned int n = 0;
_Bool prime;
printf( "\nEnter a non-negative number (0-exit): " );
scanf( "%u", &n );
if ( !n ) break;
prime = n == 2 || ( n % 2 && n != 1 );
for ( unsigned i = 3; prime && i * i <= n; i += 2 )
{
prime = n % i;
}
printf( "Number %u is %s\n", n, prime ? "prime" : "composite" );
}
return 0;
}
If to enter sequentially
1 2 3 4 5 6 7 8 9 0
then the output is
Enter a non-negative number (0-exit): 1
Number 1 is composite
Enter a non-negative number (0-exit): 2
Number 2 is prime
Enter a non-negative number (0-exit): 3
Number 3 is prime
Enter a non-negative number (0-exit): 4
Number 4 is composite
Enter a non-negative number (0-exit): 5
Number 5 is prime
Enter a non-negative number (0-exit): 6
Number 6 is composite
Enter a non-negative number (0-exit): 7
Number 7 is prime
Enter a non-negative number (0-exit): 8
Number 8 is composite
Enter a non-negative number (0-exit): 9
Number 9 is composite
Enter a non-negative number (0-exit): 0
Another approach to find whether a number is prime or not can be :-`
#include<stdio.h>
void main()
{
int no,i;
char x='y';
printf("Enter a number : ");
scanf("%d",&no);
for (i=2;i<=no/i;i++)
{
if(no%i==0)
{
x='n';
break;
}
}
if(x=='y')
printf("The number is a prime number. ");
else
printf("The number is not prime number. ");
}
The logic here is to limit the number of test cases to (the quotient of the number being tested and the value of the loop counter) since a divisor cannot exceed this quotient.
Related
In my code I can only input 1 number. How to enter 4 additional numbers and determine if it's a prime or not and then display only the prime numbers.
#include<stdio.h>
int main()
{
int n, c = 2, f = 1;
printf("Enter a number:");
scanf("%d", &n);
while(c < n)
{
if(n%c == 0)
{
f = 0;
break;
}
c++;
}
if(f) printf("%d is prime number\n\n", n);
return 0;
}
Here is my output, using the code above:
Please enter a number:2
...Program finished with exit code 0
Press ENTER to exit console.
And here is the expected output:
Please enter a number:1
Please enter a number:2
2 is a prime number.
Please enter a number:3
3 is a prime number.
Please enter a number:4
Please enter a number:5
5 is a prime number.
Let's say you want to check 5 numbers whether they are prime or not.
The approach you followed, you just have to do the same for rest of the numbers.
To do that, you can run an additional loop. For example,
int inputSize = 5;
while(inputSize--)
{
printf("Enter a number:");
scanf("%d", &n);
// now check if the number is prime or not
}
Note: Don't forget to initialize the values in proper place.
Sample code:
#include<stdio.h>
int main()
{
int inputSize = 5;
while(inputSize--)
{
int n, c = 2, f = 1;
printf("Enter a number:");
scanf("%d", &n);
while(c < n)
{
if(n%c == 0)
{
f = 0;
break;
}
c++;
}
if(f) printf("%d is prime number\n\n", n);
}
return 0;
}
Check out the following resource to know more about primality of a number
https://www.studytonight.com/c-programs/c-program-to-check-whether-a-number-is-prime-or-not
It is evident that you need a loop with 5 iterations to enter 5 numbers.
As the notion of prime numbers is defined for natural numbers then you need to use an unsigned integer type to store entered numbers.
And your code is incorrect because for numbers 0 and 1 it outputs that they are prime numbers.
The program can look the following way.
#include <stdio.h>
int main( void )
{
const size_t N = 5;
for ( size_t i = 0; i < N; i++ )
{
printf( "Please enter a number: " );
unsigned int n = 0;
if ( scanf( "%u", &n ) == 1 )
{
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 3; prime && i <= n / i; i += 2 )
{
prime = n % i != 0;
}
if ( prime ) printf( "%u is a prime number.\n", n );
}
else
{
while ( getchar() != '\n' );
}
putchar( '\n' );
}
}
The program output might look like
Please enter a number: 1
Please enter a number: 2
2 is a prime number.
Please enter a number: 3
3 is a prime number.
Please enter a number: 4
Please enter a number: 5
5 is a prime number.
You need to read the numbers in a loop. You also need to check that the input really is a number. The function scanf returns the number of successfully read values. Try this:
#include <stdio.h>
int main(void)
{
int c, ch, i, m, n;
i = 0;
while (i < 5) {
printf("Enter a number: ");
m = scanf("%d", &n);
if (m == 1) {
c = 2;
while ((c < n) && (n % c != 0)) {
c++;
}
if (c == n) {
printf("%d is prime number\n", n);
}
putchar('\n');
i++;
} else {
fprintf(stderr, "Not a number\n\n");
do { ch = getchar(); } while (ch != '\n');
}
}
return 0;
}
If the input is invalid we can give the user another chance. In this case we first need to read past the unread characters which represents the invalid input.
Also note that the algorithm can be improved by only inspecting numbers up to the square root of n.
#include<stdio.h>
int main(){
int i, n, prime=0;
printf("Enter any positive integer:\n");
scanf("%d", n);
for(i=2; i<=n; i++){
if(n%i==0){
prime=1;
break;
}
}
if(n==1){
printf("1 is neither prime not composite.");
}
else{
if(prime==0){
printf("%d is a prime number.", n);
}
else{
printf("%d is not a prime number.", n);
}
}
return 0;
}
I don't know what the problem here is but it never works.
It only takes in the input but then after that just shows a blank line and then nothing happens. I also compared it with another code for the same problem online and it looked almost looked similar and I couldn't find the problem here.
Enable all compiler warnings to save time.
"%d" in scanf() expects a matching int *, not an int.
// scanf("%d", n);
scanf("%d", &n);
Code iterates too far, should iterate less than n
// for(i=2; i<=n; i++){
for(i=2; i<n; i++){
// or even better and faster
for(i=2; i<=n/i; i++){
Test Inverted?
When n%i==0 is true, it imples n is not a prime.
I tried running your program but instead of blank output, I got a Segmentation fault:
Enter any positive integer:
12
Segmentation fault (core dumped)
You need to pass address of variable rather than actual variable to scanf method, see examples here. So scanf statement which is like this:
scanf("%d", n);
becomes this:
scanf("%d", &n);
I tested and your program started giving output as expected:
c-posts : $ ./a.out
Enter any positive integer:
14
14 is not a prime number.
Edit:
From #Jabberwocky's comment I noticed that your prime number calculation logic seems doesn't seem to be working okay. You're currently iterating from [2..n] . Note that n%(i=n) would always be zero. You need to exclude n from loop range like this:
for(i=2; i < n; i++){
// ...
}
Or you can also iterate till sqrt(n) which would have less iterations:
for(i=2; i< sqrt(n); i++){
// ...
}
make it:
scanf("%d", &n);
For starters the argument of the call of scanf is incorrect.
scanf("%d", n);
You have to write
scanf("%d", &n);
Also there is no great sense to use a signed integer number to check whether it is a prime number. Use an unsigned integer type as for example unsigned int.
And any prime number is divisible by itself. So due to the condition in the for loop
for(i=2; i<=n; i++){
the variable prime will be always set to 1 because when i is equal to n then n % i is equal to 0.
Change the for loop the following way
for( i = 2; prime == 0 && i <= n / i; i++ )
{
if ( n % i == 0 ) prime = 1;
}
However if the number is an even number and is not equal to 2 then it is clear that it is not a prime number. You can check this before the for loop to skip it for even numbers.
Pay attention to that the user can enter 0. In this case your program will output that 0 is a prime number though it is not a prime number.
The program can look the following way
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
printf( "Enter any positive integer: " );
scanf( "%u", &n);
int prime = n % 2 == 0 ? n == 2 : n != 1;
for ( unsigned int i = 2; prime && i <= n / i; i++ )
{
if ( n % i == 0 ) prime = 0;
}
if ( n < 2 )
{
printf( "%u is neither prime not composite.\n", n );
}
else if ( prime )
{
printf( "%u is a prime number.\n", n );
}
else
{
printf( "%u is not a prime number.\n", n );
}
return 0;
}
i want to take number from user then print if it prime or not but i can't find what is error where result always not prime so what is problem??
#include <stdio.h>
int main(void)
{
int number;
char flag = 0;
printf("Please enter the number:");
scanf("%d",&number);
for (int i = 1; i <= number; i++) {
if (number %i == 0) {
flag = 1;
break;
}
}
if (number==1)
printf("%d neither prime nor not prime", number);
if (flag==1)
printf("%d is not prime",number);
else
printf("%d is prime",number);
return 0;
}
Take a look at the loop condition here:
for(int i=1;i<=number;i++)
With <=, i goes up to number. So the last check will be if(number%number==0), which is always true: your program says that 5 is not a prime number because 5 divided by 5 has remainder 0. The same applies to dividing the number by 1 (which also results in no remainder), so this check should start at 2. This line should be:
for(int i=2;i<number;i++)
Typically i only has to go up to sqrt(number) because no two numbers bigger than the root of number multiplied will result in number.
Also, if the number entered is 1, you get two of the three possible outputs instead of just the first one. To fix this, put an else before the if (flag == 1).
edit to work successfully
#include <stdio.h>
int main(void)
{
int number ;
char flag=0;
printf("please enter the number:");
scanf("%d",&number);
for(int i=2;i<number;i++)
{
if(number%i==0)
{
flag=1;
break;
}
}
if (number==1)
{ printf("%d neither prime nor not prime", number);}
else if (flag==1)
{ printf("%d is not prime",number);}
else
{ printf("%d is prime",number);}
return 0;
}
Just check reminder either it is 0 or 1, if you divide any number in the end it will give you either 0 or 1 in reminder.If reminder is 1 so number is prime or 0 number is not prime.
#include <stdio.h>
int main(void)
{
int number ;
char flag=0;
printf("please enter the number:");
scanf("%d",&number);
if((number>2)&&(number%2==0))
{
flag=1;
}
if (number==1)
{ printf("%d neither prime nor not prime", number);}
if (flag==1)
{ printf("%d is not prime",number);}
else
{ printf("%d is prime",number);}
return 0;
}
In fact my teacher has passed the program that calculates the prime numbers from 1 to N. But I did not understand some things in the code and would like to help.
In line 18 we have the following: for(j=2; j<=i/2; j++), because j was divided by 2? and why j start in 2? should not start i and j on 1?
#include <stdio.h>
int main() {
int i, j, n, isPrime; //isPrime is used as flag variable
/* Reads upper limit to print prime */
printf("Find prime numbers between 1 to : ");
scanf("%d", &n);
printf("\nAll prime numbers between 1 to %d are:\n", n);
/* Finds all Prime numbers between 1 to n */
for(i=2; i<=n; i++) {
/* Assume that the current number is Prime */
isPrime = 1;
/* Check if the current number i is prime or not */
for(j=2; j<=i/2; j++) {
/*
* If i is divisible by any number other than 1 and self
* then it is not prime number
*/
if(i%j==0) {
isPrime = 0;
break;
}
}
/* If the number is prime then print */
if(isPrime==1) {
printf("%d is Prime number\n", i);
}
}
return 0;
}
should not start i ... on 1?
Yes, i should at 1. Consider that the current code will evolve. Later code may look like the below. Notice the comment and code matches your contract "numbers between 1 and N". No implied short-cut starting at 2, but clarity that code is properly testing all numbers [1...N].
/* Finds all Prime numbers between 1 to n */
for(i=1; i<=n; i++) {
if (IsPrime(i)) {
printf("%d is Prime number\n", i);
}
}
The point is that as a programmer, you are given the task "Finding prime number between 1 and N". A common sub-task is to code bool IsPrime(int i). Certainly if you code everything together, i can start at 2 - we know 1 is not a prime. Yet good programming begins with software architecture and that involves divide and conquer. So making a stand-alone helper function that works for all input is a good first step.
should not start j ... on 1?
No. Now code is into its find-a-prime algorithm and starting j=1 would fail.
bool IsPrime(int i) {
if (i <= 1) return false; // Cope with negative, 0, and 1.
for (int j=2; j<=i/2; j++) {
if (i%j==0) {
return false;
}
}
return true;
}
Of course, we can optimize IsPrime() in many ways.
The first prime number is 2 -- which is why you start as 2 -- everything is divisible by 1, and if you start there your algo will fail.
You end with N/2 because testing larger number will not result in anything that you would not have found, simply because to be a non-prime means that you will have to have to have at least 2 factors, and the smallest prime is 2 and 2*(i/2) >= i -- but in reality it is better and safe to stop at square root of N (but maybe that is in the next lesson).
This starting at 2 and increment the loop by one is wasteful -- since all primes except 2 is odd it would be better to start at 3 and increment by 2, and just make a special test for dividing by 2 outside the loop.
The first prime number is known to be 2, so there is no reason to start with 1. Given number i, there is no reason to try to divide it by numbers greater than its half, as the result will always be less than 2 and yield a quotient of 0 and a non-zero remainder (unless we divide it by itself, which is pointless in the prime test).
This is the easiest way:
#include <iostream>
using namespace std;
int main (){
int first,second;
cout<<"Enter starting of limit";
cin>>first; //First value
cout<<"Enter Ending of limit";
cin>>second; //Second value
L:
if(first < second){ //Checking starts here
if(first % 2 != 0 && first % 5 != 0 || first - 5 == 0 && first % 7 != 0){
cout<<first<<endl;
first++ ;
goto L; //Iteration
}
}
}
#include<stdio.h>
int main()
{
int num,i,count,n;
printf("Enter max range:");
scanf("%d",&n);
for(num=1; num<=n; num++)
{
count=0;
for(i=2; i<=num/2; i++)
{
if(num%i==0)
{
count++;
break;
}
}
if(count==0 && num!=1)
printf("%d ",num);
}
return 0;
}
I am making a program where the user enters a positive integer between 2 and 1000000, and if it is a prime number it prints "The number is a prime number" and if it isn't a prime number it prints the factorization of the number. I'm trying to put multiplication signs in between my factors, but can't figure it out! (ie: user inputs 24, program outputs 2 2 2 3, I want it to output 2x2x2x3). Any ideas? I have been trying for ages
#include <stdio.h>
int main()
{
int N, a, divide, flag=0;
printf("Please enter a positive integer ");
scanf("%d",&N);
if (N<2||N>1000000)
{
printf("Error!");
return 0;
}
for(a=2;a<=N/2;++a)
{
if(N%a==0)
{
flag=1;
break;
}
}
if (flag==0)
printf("The number %d is a prime number.", N);
else
{
printf("The number %d is not a prime number.\nThe prime factors of %d are:",N, N);
divide = 2;
while(N!=0&&flag==1){
if(N%divide!=0)
divide = divide + 1;
else {
N = N / divide;
printf("%d",divide);
if(N==1)
break;
}
}
}
return 0;
}
If you revers the problem, you need to print a "x" before your numbers, appart for the 1st one.
So just have a int first=1;. In the loop add:
if (first) {
first = 0; // no more 1st loop
} else {
printf("x"); // print a "x" before printing the next number
}
Just change your printf:
printf("%d%c", divide, (N > 1) ? 'x' : '\n');
which prints '\n' (carriage return) if you're on the last iteration, or 'x' if you're not.