I have this code in which I need to find all prime numbers from 2 to 1000 and need to print them out in groups of 5 in each line. How can I do that?
#include <stdio.h>
int main() {
int i, a, count;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i ) {
count = 0;
for (a = 1; a <= i; a ) {
if (i % a == 0)
count ;
}
if (count == 2)
printf("%d\t", i);
}
return 0;
}
CodePudding user response:
You can add a new counter
to count the number of prime numbers printed until the current loop. If this counter value is divisable by 5
, print a new line.
int main()
{
int i,a,count;
printf("Prime numbers between 2 and 1000 are : \n");
int cnt_prime = 0; // count the number of prime numbers until this loop
for (i=2;i<1000;i )
{
count=0;
for (a=1;a<=i;a )
{
if (i%a==0)
count ;
}
if (count==2) {
printf("%d\t", i);
cnt_prime ;
if (cnt_prime % 5 == 0) // print new line after each five numbers
printf("\n");
}
}
return 0;
}
There is another faster approach to find the prime numbers in a range. You can read about sieve of eratosthenes from here: https://www.geeksforgeeks.org/sieve-of-eratosthenes/
CodePudding user response:
Maybe not the best answer, but you could add another counter-variable called prime_count
and initialize it with value 0
. Then each time you print a prime, you increment that variable. After printing a prime you then check wether prime_count
is equal to 4
. If that's the case you print a newline-character and reset prime_counter
to 0
.
The code could look something like this:
int main()
{
int i,a,count,prime_count=0;
printf("Prime numbers between 2 and 1000 are : \n");
for (i=2;i<1000;i )
{
count=0;
for (a=1;a<=i;a )
{
if (i%a==0)
count ;
}
if (count==2)
{
printf("%d\t",i);
prime_count ;
if (prime_count == 4)
{
printf("\n");
prime_count = 0;
}
}
}
return 0;
}
CodePudding user response:
You can check till square root of N to verify prime no need to check till N it makes your code O(sqrt(n)) refer this for more info about the algorithm.You can have a variable called printCounter to check total elements printed on console when it become a multiple of 5 we can print a new line.
int main() {
int i, a, printCount = 0 ;
printf("Prime numbers between 2 and 1000 are : \n");
for (i = 2; i < 1000; i ) {
int isPrime = 1;
for (a = 2; a * a <= i; a ) {
if (i % a == 0){
isPrime = 0;
break;
}
}
if (isPrime == 1) {
printf("%d\t", i);
printCount ;
}
if(printCount%5 == 0){
printf("\n");
}
}
return 0;
}