I've been trying for last 3 days to overcome the problem but I'm failing continuously.
I'm trying to print all prime numbers from 1 to 300 in C.(Dev C++)
below is the code
#include <stdio.h>
#include <conio.h>
main() {
// 1 - 300
register int i, j;
for (i = 1; i <= 300; i++) {
for (j = 2; j < i; j++) {
if (i % j == 0) {
break;
} else {
printf("\n%d", i);
break;
}
}
}
}
please help me in this and also help me to clear the concept.
Thanks.
You are printing the numbers too early. Print the numbers at the end of the outer loop. ie, after the inner loop.
You could do
for(i=1; i<=300; i++)
{
for(j=2; j<i; j++)
{
if(i%j == 0)
{
break;
}
}
if(j>=i)
{
printf("\n%d",i);
}
}
If at the end of inner loop, the condition j<i still holds, the loop was terminated prematurely due to the break statement being executed and hence the number is not prime.
But if that condition is false, ie, if j>=i is true, the number is prime.
You could also do this with the help of a flag variable.
And you probably don't need to use the register storage class specifier. See this post.
And there's no need of the break statements. In the program you've posted,
if(i%j == 0)
{
break;
}
else
{
printf("\n%d",i);
break;
}
is same as
if(i%j == 0)
{
break;
}
printf("\n%d",i);
or just
if(i%j != 0)
{
printf("\n%d",i);
}
For primes up to 300, the Sieve of Eratosthenes algorithm is quite good.
This should do the work for now, but I am sure that there are more efficient ways for doing this job:
int main() {
int i, j;
char is_prime; // indicator for each number if it is a prime number
printf("2\n"); // first number in the series, and the only one witch is even
for (i = 3; i<=300; i += 2) // When I jump in 2 numbers each time, I save the check of all the even numbers, that we knows ahead that they are not prime numbers.
{
is_prime = 1; // Start with an assumption that the number is prime. If we will find out that it doesn't, we will turn this value to 0.
for (j = 3; j < i; j++)
{
if(i % j == 0)
{ // If this number fully divided by this `j` value, so it is not a prime number.
is_prime = 0; // Turn this variable to indicate that this is not a prime number.
break; // This loop is for testing the current number. Now we found out that it is not a prime number, so we can end this loop.
}
} // End of the inner loop that check if the current 'i' number is a prime number.
if (is_prime) { // If we found that the current 'i' number is a prime number (if is_prime != 0)
printf("%d\n", i); // Print the 'i' number.
}
}
return 0;
}
Generating prime numbers
This is the simplest way to achieve this
for(i=2 ; i <= n ; i++)
{
for(j=2 ; j<i ;j++)
{
if(i%j == 0)
break ;
}
if(i == j )
printf("%d\n",i);
}
#include<stdio.h>
void main()
{
int n,i,fact,j;
printf("Enter the Number");
scanf("%d",&n);
printf("Prime Numbers are: \n");
for(i=1; i<=n; i++)
{
fact=0;
for(j=1; j<=n; j++)
{
if(i%j==0)
fact++;
}
if(fact==2)
printf("%d " ,i);
}
getch();
}
Try to solve it your self, putting values of i and j respectively, you'll find the errors.
1.Declare a variable int and initialize it by 0 (int a=0).
2.Then in the inner for loop in the if statement increase the value of a for each division.
If(i÷j==0)
{a=a+1;//or a++
}
3.Get out of the loop now and look if the value of the a is still 0 then i is a prime else it's not!
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 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;
}
OK so I got this challenge where I have to print all the primes from 1 to 100... However there is an error in my code that I am unable to find. Here is how I thought the problem should be done:
For any number from 3 to 100 check if there is any other number in the primes array that divides it. If there is the number is not prime. If there is not the number is prime and should be added to the array. Pretty simple, right ?
However it is not working.
Here is my code :
#include <stdio.h>
int main() {
int Primes[50] = {0};
int i, j, k;
Primes[0] = 2;
Primes[1] = 3;
for (i = 3; i < 101; i++) {
for (j = 2; j < 100; j++) {
if (i % Primes[j] != 0 && Primes[j] != 0) {
Primes[j] = i;
}
}
}
printf("Primes array : \n");
for (k = 0; k < 51; k++) {
printf("%d ", Primes[k]);
}
return 0;
}
instead of assuming the magic number as 25... that is k!=25, we can
replace it with i<=100.
#include <stdio.h>
#include <stdlib.h>
int main(void){
int Primes[50] = {0};
int i,j,k = 0;
Primes[0]=2;
Primes[1]=3;
for(i=0; i<=100; i++) {
for(j = 2; j<=i; j++) {
if(i % j == 0 ){
if(i == j)
Primes[k++]=i;
break;
}
}
}
printf("Primes array : \n");
for(int index = 0;index < k; index++) {
printf("%d\n", Primes[index]);
}
return 0;
}
When you do this:
if(i % Primes[j] != 0 && Primes[j] !=0)
{
Primes[j]=i;
}
You're saying "if the current number is not divisible by the given prime number, replace the given prime number with the current number". This is not what you want.
You need to check if the current number is not divisible by any prime number. So you need to loop though the list of primes to make sure your number isn't divisible by any of them, and if so add the number to the end of the list. You can do that as follows:
int num_primes = 0;
for (i=2;i<101;i++)
{
int is_prime = 1;
for(j=0; j<num_primes && is_prime; j++)
{
if(i % Primes[j] == 0)
{
is_prime = 0;
}
}
if (is_prime) {
Primes[num_primes++] = i;
}
}
In the above code, we use num_primes to count the number of primes we have so far, and is_prime to see if we found a prime that divides the current number. As you divide each number by a prime, if the remainder is 0 you know the number is not prime and set is_prime to 0. This also causes the inner loop to exit right away. Then if is_prime is still set at the end of the inner loop, you have a prime and you add it to the end of the list.
You also have an off-by-one error in the printing loop:
for(k=0;k<51;k++)
Since Primes has size 50, the largest valid index is 49. So change it to:
for(k=0;k<50;k++)
There are lot of issues in the algorithm you used. Use this simple version with issues addressed in the code.
int main(void){
int Primes[50] = {0};
int i,j,k = 0 /* use for prime count purpose */;
Primes[0]=2;
Primes[1]=3;
for(i=4 /* 3 is already stored */; k != 48; i++) { /* rotate loop until prime count doesn't reaches 48 */
for(j = 2; j<=i; j++) { /* i is the number you want to check whether its prime or not. SO rotate loop from 2 to "i" */
if(i % j == 0){ /* use i%j not i % Primes[j] as you want to check whether i is prime or not */
if(i == j) /* if its a prime numbur j reaches upto i */
Primes[k++]=i; /* store it */
break; /* comes out of inner loop */
}
}
}
printf("Primes array : \n");
for(int index = 0;index < k; index++) { /* rotate k times not some random 51 times */
printf("%d ", Primes[index]);
}
return 0;
}
The code above doesn't actually give what we want, but beautiful code nonetheless. Here is the edited code that gives the prime numbers from 1 to 100
int main(void){
int Primes[50] = {0};
int i,j,k = 0 /* use for prime count purpose */;
Primes[0]=2;
Primes[1]=3;
for(i=0 /* 3 is already stored */; k != 25; i++) { /* rotate loop until prime count doesn't reaches 48 */
for(j = 2; j<=i; j++) { /* i is the number you want to check whether its prime or not. SO rotate loop from 2 to "i" */
if(i % j == 0){ /* use i%j not i % Primes[j] as you want to check whether i is prime or not */
if(i == j) /* if its a prime numbur j reaches upto i */
Primes[k++]=i; /* store it */
break; /* comes out of inner loop */
}
}
}
printf("Primes array : \n");
for(int index = 0;index < k; index++) { /* rotate k times not some random 51 times */
printf("%d\n", Primes[index]);
}
return 0;
}
I'm trying to print the Prime numbers between a given range but I get blank output. Where have I gone wrong? Is it a logic mistake or implementation mistake?
#include <stdio.h>
int isPrime(int i)
{
int j;
for(j=2; j<=i; j++)
{
if(i%j==0)
{
return 0;
}
}
return 1;
}
int main()
{
int cases, n1, n2, i;
scanf("%d", &cases);
while(cases>0)
{
scanf("%d%d", &n1, &n2);
for(i=n1; i<=n2; i++)
{
if(isPrime(i))
{
printf("%d\t", i);
}
}
cases--;
}
return 0;
}
You must stop the loop in isPrime before i because all non zero numbers are divisible by themselves:
int isPrime(int i) {
int j;
for (j = 2; j < i; j++) {
if (i % j == 0) {
return 0;
}
}
return 1;
}
Note that you should also return 0 for numbers below 2. Furthermore, you can improve performance dramatically by stopping at the square root of i and by testing only odd numbers above 2.
int isPrime(int i) {
if (i <= 2) {
return i == 2;
}
for (int j = 3; j * j <= i; j += 2) {
if (i % j == 0) {
return 0;
}
}
return 1;
}
i%i==0 will be always true unless i is zero, so isPrime will return 0 for whatever i which is 2 or greater.
You can use j<i instead of j<=i, for example.
Another point is that your isPrime will mistakenly judge all integers that is 1 or less as primes, so you should check for them before the loop.
Apart from being sub-optimal, your code goes all the way to i when trying to find the divisor. This means that all checks will eventually succeed when i == j, so i%j is zero.
A better stopping condition for the loop is
for( j=2 ; j*j <= i ; j++)
In other words, stop upon passing the square root of i. This is valid, because if you have not found proper divisors smaller than the square root, then it is guaranteed that there are also no divisors larger than the square root.
If you know the upper limit for n2, you could make your solution even faster by pre-computing all primes up to sqrt(n2), and using them to test whether other numbers are prime or not.
For starters 2 is a prime number. And every number is divisible by itself. So this condition
if(i%j==0)
will be always equal to true when j is equal to i.
The function can be written the following way
int isPrime( unsigned int x )
{
int prime = ( x == 2 ) || ( x % 2 != 0 && x > 2 );
for ( unsigned int i = 3; prime && i * i <= x; i += 2 )
{
prime = x % i != 0;
}
return prime;
}