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;
}
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/
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;
}
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;
}
Related
This program is supposed to print the first x prime numbers, but I noticed that it was printing some non-prime numbers, such as 27 or 35.
I've been looking at it for hours and nothing seems to pop up. So please, if you know what's wrong, tell me.
#include <stdio.h>
int main(){
int i=0, cont=2, prim=2, quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
while(i<quant){
if(prim%cont!=0 && (cont>1 && cont<prim)){
cont++;
}
else if(prim%cont==0 && (cont>1 && cont<prim)){
prim++;
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
return 0;
}
UPDATE
Wow, ok, so after 7 years people still stumble upon this question.
In the last 7 years my coding ability has improved somewhat, and now I see how inefficient this program was. Just in case anyone might be trying to find the solution for this and the stumble upon this, here are three solutions much easier and better, and why they work.
Solution 1:
This first solution is very inefficient too, but it works, and is pretty simple to understand. Basically what you have to do is check if each number up to the upper limit is prime or not. To do so, just check if it is divisible by any number up to its square root.
Why its squared root? Because the square root squared is equal to the number, which means that if the number was not divisible up to its square root, it won't be divisible by any number above it, as for it to be divisible by it, it needs to multiply by a smaller number. For example, the squared root of 36 is 6, and 36 is divisible by 9, as 9*4=36. But since 9 is above 6 (which is the squared root), the number that multiplied by 9 gives us 36 is below, and as such, we have already seen that it is not prime, as we have already checked that 36 is divisible by 4. This being said, if no number below the squared root of a number is a natural dividend of the number, than that number is prime.
#include <stdio.h>
int isPrime(int num) {
for (int i = 2; i*i <= num; i++) {
if (num%i==0) {
return 0;
}
}
return 1;
}
void getPrimes(int num) {
int cont = 0;
for (int i = 2; cont < num; i++) {
if (isPrime(i)==1) {
printf("%d\n", i);
cont++;
}
}
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
This is inefficient as we are checking if the number is divisible by numbers that won't influence (more on this in the next solution).
Solution 2:
In this second solution, which is more elegant in my opinion, we give use to the Fundamental Theorem of Arithmetic, which states that any number greater than 1 is either a prime number itself, or can be represented by factorizing into the multiplication of prime numbers. This means that if a number is divisible by a non prime number, it is also divisible by the prime numbers that make it up, and thus we only need to check if the number in question is divisible by smaller prime numbers than itself. For this purpose, we store the prime numbers in an array.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; i < cont; i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Solution 3:
This final solution is a mix of the two above. Solution 1 checked numbers that weren't prime, having redundancy, and the solution 2 checked numbers above the square root, which can never be a dividend if the smaller numbers aren't. In this solution, we check if the number is divisible only by prime numbers below the squared root.
#include <stdio.h>
void getPrimes(int num) {
int primes[num];
int cont = 1;
primes[0] = 2;
int current = primes[cont-1]+1;
while (cont < num) {
int before = current;
for (int i = 0; (i < cont && primes[i]*primes[i] <= current); i++) {
if (current%primes[i]==0) {
current++;
break;
}
}
if (before == current) {
primes[cont] = current;
cont++;
current++;
}
}
for (int i = 0; i < cont; i++) {
printf("%d ", primes[i]);
}
printf("\n");
}
int main() {
int quant;
printf("Insert number of prime numbers you wish: ");
scanf("%d", &quant);
printf("The first %d prime numbers are:\n", quant);
getPrimes(quant);
return 0;
}
Comparing the execution times of each algorithm for 100 prime numbers, we obtain the following results
Algorithm 1
Algorithm 2
Algorithm 3
0.048 ms
0.068 ms
0.039 ms
Comparing to the algorithm of the original post which takes 0.599 ms, every one of these new solutions is more efficient (the worst being around 10x better), and actually calculates the real values.
Try this
#include<stdio.h>
int prime(int n)
{
int i, j, len=1, brk=0;
int list[200]={2};
for(i=2; i<=n; i++)
{
for(j=0; j<len; j++)
{
if(i%list[j]==0){
brk=1;
break;
}
else
{
brk=0;
}
}
if(brk==0)
{
list[len]=i;
len++;
}
}
for(i=0; i<len; i++)
printf("%d ",list[i]);
}
main()
{
int i, n;
scanf("%d",&n);
prime(n);
}
#PKDOJ If the series is set within 30. You can go blindly with the logic below. But nothing above that series. Adding i%11 clears the 77 as well. Not efficient
if ((i % 2) && (i % 3) && (i % 5)&&(i%7)&&(i%11))
Code:
int count = 0, quant = 5, i, j;
int flag = 0;
for(prim = 2 ; count <= quant ; prim ++) {
flag = 0;
for(j = 2; j < prim/2; j++) {
if(prim % j == 0) {
flag = 1;
break;
}
}
if(flag == 0) {
printf("%d\n", prim);
count++;
}
}
Update your code as:
while(i<quant){
if(cont<prim) {
if(prim%cont!=0) {
cont++;
} else {
prim++;
cont = 2; // restart cont
}
}
else if(prim%cont==0 && cont==prim){
printf("%d\n", prim);
prim++;
cont=2;
i++;
}
}
Simple way is to find is: if a number is not divisible by 2,3 & 5, its a prime number.
#include <stdio.h>
int main()
{
int num = 35;
int i = 5;
printf("1 2 3 5");
while (i <= num)
{
if ((i % 2) && (i % 3) && (i % 5))
{
printf(" %d",i);
}
i++;
}
printf("\n");
return 0;
}
// C Program to Print Prime Numbers From 1 to 100
#include
int main() {
int i, num, count;
// Checking for prime numbers
for (num = 1; num <= 100; num++) {
count = 0;
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
count++;
break;
}
}
// Checking and Printing Prime Numbers
if (count == 0 && num != 1) {
printf("%d \n", num);
}
}
return 0;
}
I don't understand, if I put 0 at the start of the count variable (i.e., int i, num, count=0; like this) the code is not working. But if you put count=0 inside the for loop it is working. Why is this happening?
I wonder if you wrote that code yourself.
Why did you add count variable to start with if you do not seem to know how it works?
I don't understand, if I put 0 at the start of the count variable (i.e., int i, num, count=0; like this) the code is not working. But if you put count=0 inside the for loop it is working. Why is this happening?
That variable is used to detect if any value of i is found where num is a multiple of i. If that is the case (count != 0 it is not a prime.
Of course you need to do this for each number num which means you must reset count for each iteration of the outer loop.
If you only do it once where you define the variable, it will never find any prime number any more after you saw the first none-prime number.
Working code:
// C Program to Print Prime Numbers From 1 to 100
#include
int main(void) {
int i, num, count;
// Checking for prime numbers
for (num = 2; num <= 100; num++) {
count = 0; // This is the indicator whether a number is prime
// We must reset it here for each number we check.
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
count++;
break;
}
}
// Checking and Printing Prime Numbers
if (count == 0) {
printf("%d \n", num);
}
}
return 0;
}
Broken code:
// C Program to Print Prime Numbers From 1 to 100
#include
int main(void) {
int i, num, count = 0; // This is only set to 0 once for all numbers we check.
// Checking for prime numbers
for (num = 2; num <= 100; num++) {
for (i = 2; i <= num/2; i++) {
if (num % i == 0) {
count++; // count will never become 0 again.
// We will not be able to detect any prime number after this.
break;
}
}
// Checking and Printing Prime Numbers
if (count == 0) {
printf("%d \n", num);
}
}
return 0;
}
Not related to your problem but some detail to improve the code:
Why do you start with num=1 if you later check num != 1?
Instead start at num=2.
Or print 2 before you start the loop. Then run the loop from num=3 and increment num+=2 to only check the odd numbers.
I have return the code to find a factorial and to display trailing zeros at the end of the factorial, but the output is wrong... could you please help me to find the mistake?
#include <stdio.h>
int main() {
int m = 1, i, N, count = 0;
scanf("%d", &N);
for (i = 1; i <= N; i++) {
m = m * i;
}
printf("%d", m);
while (m > 0) {
if ((m % 10) == 0) {
count = count + 1;
m = m / 10;
}
break;
}
printf("%d", count);
return 0;
}
Your code only works for very small values of N: up to 9. For slightly larger values, you would need to add an else keyword before the break statement and you would get a correct result for a few more cases.
For larger values, you must compute the power of 5 that divides the factorial. You can do this incrementally by summing the power of 5 that divide each individual number up to and including N.
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
/* only consider factors that are multiples of 5 */
count = 0;
for (int i = 5; i <= N; i += 5) {
for (int j = i; j % 5 == 0; j /= 5)
count++;
}
printf("%d\n", count);
return 0;
}
An even simpler and faster solution is this: compute the number of multiples of 5 less or equal to N, add the number of multiples of 5*5, etc.
Here is the code:
#include <stdio.h>
int main() {
int N, count;
if (scanf("%d", &N) != 1)
return 1;
count = 0;
for (int i = N; (i /= 5) > 0;) {
count += i;
}
printf("%d\n", count);
return 0;
}
you have two problems
your collapse the two outputs so you see only one of them / you cannot see who is who, just add a separator between them
an else is missing when you count so you count to only up to 1 and the result is wrong from factorial 10
So the minimal changes produce :
int main()
{
int m=1,i,N,count=0;
scanf("%d",&N);
for(i=1;i<=N;i++)
{
m=m*i;
}
printf("%d\n",m); /* <<< added \n */
while(m>0)
{
if((m%10)==0)
{
count=count+1;
m=m/10;
}
else /* <<< added else */
break;
}
printf("%d\n",count); /* <<< added \n */
return 0;
}
after the changes :
pi#raspberrypi:/tmp $ ./a.out
5
120
1
pi#raspberrypi:/tmp $ ./a.out
10
3628800
2
Of course that supposes first you are able to compute the factorial without overflow
I also encourage you to check a value was read by scanf, checking it returns 1
#include <stdio.h>
int main()
{
int n,i,f=1,t,c=0;
printf("Enter number ");
scanf("%d",&n);
t=n;
for(i=1;t>=5;i++)
{
t=n/5;
c=c+t;
n=t;
}
printf("number of zeros are %d",c);
return 0;
}
I'm writing a program to determine whether or not a given number is a prime number or a composite. My code below is what i have so far. I'm thinking that using a WHILE LOOP wouldn't be as efficient as a FOR LOOP but i may be wrong.
#include <stdio.h>
int main(int argc, const char* argv[]) {
int num, i;
printf("Enter a number you want to check:");
scanf("%d", &num);
if (num == 1) {
printf("%d is neither prime nor composite", num);
}
i = 2;
while (i <= num - 1) {
if (num % i == 0) {
printf("%d is composite\n\n", num);
break;
}
}
}
The program works with most even numbers but when I get to, say 9 I don't get a return because it's not dividing by three. Could i add into this WHILE LOOP to compensate or would i be easier to use a FOR LOOP?
I'm thinking that if i used a FOR LOOP i could start it off sort of like this.
for (i = 2, i <= num, i++) {
num % i == 0;
}
printf("%d is Composite", num);
}
you have forgotten to increase the index inside your loop
while (i <= num-1) {
if (num%i==0)
{
printf("%d is composite\n\n",num);
return; // test is finished
}
i++; // increase i by 1
}
printf("%d is prime number\n", num); // add this line to display the prime numbers also
EDIT
I just came to see your comment about the use of for loop :
for (i = 2; i < num; i++) // ① be careful of ; and , ② i<num not i<=num
{
if(num % i == 0) // if your num is dividable ==> not prime
{
printf("%d is Composite", num);
return 0; // return from the main func
}
}
printf("%d is prime number\n", num); // no divisor = no return = prime number
EDIT 2
Now let's talk about efficiency :
to determine whether the number is prime or not, you can iterate for less than even half of it, how ?
if p is the number and k is its divisor then :
p = k * n
if ( n > sqrt(p) && k > sqrt(p))
==> n * k > p
take any pair of divisors for any integer, both the divisors cannot be greater than the square root of the integer at the same time!
that's why you can iterate like this:
while (i <= sqrt(num)) {
if (num%i==0)
{
printf("%d is composite\n\n",num);
return; // test is finished
}
i++; // increase i by 1
}
So for your 10000 you only iterate 100 time! and not 5000 as you thought ;)
FURTHER
If you're really on a tight budget, you can check only for odd numbers greater than 2 :D, I mean if it was not dividable by 2 then it'll never be dividable by 4, 6, 8 ... skip them
Example :
if(num%2 == 0) // check for 2
{
printf("%d is composite\n\n",num);
return;
}
while (i <= sqrt(num)) // check only for odd # greater than 2
{
if (num%i==0)
{
printf("%d is composite\n",num);
return; // test is finished
}
i+=2; // increase i by 2
}
printf("%d is prime\n", num);
Where you wrote:
for (i = 2, i <= num, i++)
you want:
for (i = 2; i < num; i++)
you might also think about why this:
for (i = 2, i*i <= num, i++)
might be a big win...
I'm very new to programming and I was asked to find the sum of prime numbers in a given range, using a while loop. If The input is 5, the answer should be 28 (2+3+5+7+11). I tried writing the code but it seems that the logic isn't right.
CODE
#include <stdio.h>
int main()
{
int range,test;
int sum = 2;
int n = 3;
printf("Enter the range.");
scanf("%i",range);
while (range > 0)
{
int i =2;
while(i<n)
{
test = n%i;
if (test==0)
{
goto end;
}
i++;
}
if (test != 0)
{
sum = sum + test;
range--;
}
end:
n++;
}
printf("The sum is %i",sum);
return 0;
}
It would be nice if you could point out my mistake and possibly tell me how to go about from there.
first of all, in the scanf use &range and not range
scanf("%i",&range);
Second this instruction is not correct
sum = sum + test;
it should be
sum = sum + n;
and also the
while (range > 0)
should be changed to
while (range > 1)
Because in your algorithm you have already put the first element of the range in the sum sum = 2 so the while should loop range - 1 times and not range times
That's all
OK, my C is really bad, but try something like the following code. Probably doesn't compile, but if it's a homework or something, you better figure it out yourself:
UPDATE: Made it a while loop as requested.
#include <stdio.h>
int main()
{
int range, test, counter, innerCounter, sum = 1;
int countPrimes = 1;
int [50] primesArray;
primesArray[0] = 1;
printf("Enter the range.");
scanf("%i",range);
counter = 2;
while (counter <= range) {
for (innerCounter = 1; innerCounter < countPrimes; innerCounter++) {
if (counter % primesArray[innerCounter] == 0)
continue;
primesArray[countPrimes + 1] = counter;
countPrimes ++;
sum += counter;
}
counter ++
}
printf("The sum is %i",sum);
return 0;
}
I haven't done C in a while, but I'd make a few functions to simplify your logic:
#include <stdio.h>
#include <math.h>
int is_prime(n) {
int i;
for (i = 2; i <= sqrt(n); i++) {
if (n % i == 0) {
return 0;
}
}
return 1;
}
int main() {
int range, i, sum, num_primes = 0;
printf("Enter the range: ");
scanf("%d", &range);
for (i = 2; num_primes < range; i++) {
if (is_prime(i)) {
sum += i;
num_primes++;
}
}
printf("The sum is %d", sum);
return 0;
}
Using goto and shoving all of your code into main() will make your program hard to debug.
Copy - pasted from here.
#include <stdio.h>
int main() {
int i, n, count = 0, value = 2, flag = 1, total = 0;
/* get the input value n from the user */
printf("Enter the value for n:");
scanf("%d", &n);
/* calculate the sum of first n prime nos */
while (count < n) {
for (i = 2; i <= value - 1; i++) {
if (value % i == 0) {
flag = 0;
break;
}
}
if (flag) {
total = total + value;
count++;
}
value++;
flag = 1;
}
/* print the sum of first n prime numbers */
printf("Sum of first %d prime numbers is %d\n", n, total);
return 0;
}
Output:
Enter the value for n:5
Sum of first 5 prime numbers is 28
Try the simplest approach over here. Check C program to find sum of all prime between 1 and n numbers.
CODE
#include <stdio.h>
int main()
{
int i, j, n, isPrime, sum=0;
/*
* Reads a number from user
*/
printf("Find sum of all prime between 1 to : ");
scanf("%d", &n);
/*
* Finds all prime numbers between 1 to n
*/
for(i=2; i<=n; i++)
{
/*
* Checks if the current number i is Prime or not
*/
isPrime = 1;
for(j=2; j<=i/2 ;j++)
{
if(i%j==0)
{
isPrime = 0;
break;
}
}
/*
* If i is Prime then add to sum
*/
if(isPrime==1)
{
sum += i;
}
}
printf("Sum of all prime numbers between 1 to %d = %d", n, sum);
return 0;
}