Using this code in C to implement the sieve of Eratosthenes, how can I output th
ID: 672079 • Letter: U
Question
Using this code in C to implement the sieve of Eratosthenes, how can I output the numbers using linefeed ( ) so that the numbers output 14-16 across and then drop to a new line instead of printing all down the left side?
#include <stdio.h>
#include <stdlib.h>
void main()
{
int num1, lim, i, j, flag, temp, count = 0;
printf("enter the limit");
scanf("%d", &lim);
num1=1;
if (lim < 2)
{
printf("There are no primes upto %d ", lim);
exit(0);
}
printf("Prime numbers are ");
temp = num1;
if ( num1 % 2 == 0)
{
num1++;
}
for (i = num1; i <= lim; i = i + 2)
{
flag = 0;
for (j = 2; j <= i / 2; j++)
{
if ((i % j) == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
printf("%d ", i);
count++;
}
}
printf("Number of primes between %d ", count);
}
Explanation / Answer
#include <stdio.h>
#include <stdlib.h>
void main()
{
int num1, lim, i, j, flag, temp, count = 0;
int newlineFlag = 0;
printf("enter the limit");
scanf("%d", &lim);
num1=1;
if (lim < 2)
{
printf("There are no primes upto %d ", lim);
exit(0);
}
printf("Prime numbers are ");
temp = num1;
if ( num1 % 2 == 0)
{
num1++;
}
for (i = num1; i <= lim; i = i + 2)
{
flag = 0;
for (j = 2; j <= i / 2; j++)
{
if ((i % j) == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
{
if(newlineFlag == 0)
printf("%d-", i);
else
printf("%d ", i);
newlineFlag = (newlineFlag+1)%2;
count++;
}
}
printf("Number of primes between %d ", count);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.