I am writing a program to find prime numbers from 1 to 100. Please check if my code is correct or not. When I am running my code prime numbers are not getting printed. Please help.
#include <stdio.h>
#include <conio.h>
int main()
{
int i, j, flag, rem;
flag=0;
printf("2");
for(i=3; i<=100; i++)
{
for(j=2; j<=i; j++)
{
rem = i%j;
if(rem == 0)
{
flag=1;
break;
}
}
if(flag==0)
{
printf("%d", i);
}
}
getch();
return 0;
}
You have a couple of problems
First, the for(j=2;j<=i;j++) loop should be for(j=2;j<i;j++), as if j is equal to i, j % i == 0 will always be true
Second, your flag variable is not doing what you might think it is doing. As HolyBlackCat suggested this is a good opportunity to learn how to use a debugger to see what is happening. You need to reset the flag variable, because once you find a single composite number, your flag will not reset so all following numbers will be flagged as composite. Add:
for(i=3;i<=100;i++)
{
flag = 0;
for(j=2;j<=i;j++)
{
Change for (j = 2; j <= i; j++) to for (j = 2; j <= i/2; j++). You need to loop up to i/2.
int main()
{
int i, j, flag, rem;
printf("2\n");
for (i = 3; i <= 100; i++)
{
flag = 0;
for (j = 2; j <= i/2; j++)
{
if (i % j == 0)
{
flag = 1;
break;
}
}
if (flag == 0)
printf("%d\n", i);
}
getch();
return 0;
}
It is better to have a correct indentation for well-reading purposes. I added some comments in lines where you can optimize your code and I removed the unnecesary 'printf'. (\t is to write a tab space after what it is printed)
#include <stdio.h>
#include <conio.h>
int main()
{
int flag;
printf("Prime numbers: 2\t");
for(int i = 3; i <= 100; i++) // You can declare a temporal variable for the cycle
{
flag = 0; // reset the flag variable to zero when adding a new number
for(int j = 2; j < i; j++)
{
if(i%j == 0) // substitute the 'rem' variable for an operation
{
flag = 1;
break;
}
}
if(flag == 0)
{
printf("%d\t", i);
}
}
getch();
return 0;
}
The expected output will be:
Prime numbers: 2 3 5 7 11
13 17 19 23 29 31 37
41 43 47 53 59 61 67
71 73 79 83 89 97
You should reset flag at 0 each time you try a new number. Leaving the code like this, as soon as a number isn't prime, the code will never print again.
[...snip...]
for(i=3;i<=100;i++)
{
flag = 0;
for(j=2;j<=i;j++)
{
[...snip...]
The problem is flag is not set/reset correctly. and also there is a lot of scope for improvement in the code.
As you already print 2 as prime no so no need to check other even no as 2 is the only even no which is prime.
Instead of dividing form 2..n-1 we can check it for 2..n/2
Find the optimized code below:
// return 1 if no is prime else 0
int is_prime(int n)
{
for(int i = 3; i<= n/2; i+=2){
if (n%i == 0)
{
return 0;
}
}
return 1;
}
int main()
{
printf("2\n");
for(int i=3; i<=100; i+=2)
{
if (is_prime(i))
{
printf("%d\n", i);
}
}
return 0;
}
Related
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;
}
So I have to write a code for school. I did, but my outputs are not the way they asked for. This code gives me prime number between 2 different numbers. So i have to print those numbers in rows. But yeah there are getting zeros between the answers below you can see what I mean. How can I fix this?
#include <stdio.h>
int is_prime (int number)
{
int is_prime= 1, i;
if (number < 2)
{
is_prime = 0;
}
else
{
for(i = 2; (i * i) <= number; i++)
{
if ((number % i) == 0)
{
is_prime = 0;
break;
}
else
{
is_prime = 1;
}
}
}
return is_prime;
}
int main (void)
{
int lower_limit, upper_limit, i;
scanf("%d\n%d", &lower_limit, &upper_limit);
for(i = lower_limit; i <= upper_limit; i++)
{
if (is_prime (i))
{
printf("\n%d", i);
}
else
{
printf("\n%d", is_prime(i));
}
}
return 0;
}
Output
0
11
0
13
0
0
0
17
0
19
0
Reference
11
13
17
19
It's in this if block:
if (is_prime (i))
{
printf("\n%d", i);
}
else
{
printf("\n%d", is_prime(i));
}
What this says is "if the number is prime print it, otherwise print whether it is prime (which at this point you've established it's not)".
Just get rid of the else block.
If the number is prime number just print it. No else needed - even worse it is incorrect.
You can simplyfy the the is_prime function
int is_prime (int number)
{
int is_prime = number > 1, i;
for(i = 2; (i * i) <= number; i++)
{
if ((number % i) == 0)
{
is_prime = 0;
break;
}
}
return is_prime;
}
int main (void)
{
int lower_limit, upper_limit, i;
scanf("%d\n%d", &lower_limit, &upper_limit);
for(i = lower_limit; i <= upper_limit; i++)
{
if (is_prime (i))
{
printf("\n%d", i);
}
}
return 0;
}
https://godbolt.org/z/4d8qhx
Another problem: overflow.
Avoid int overflow in i*i, which is undeifned behavior (UB).
This can happen when number is a prime near INT_MAX.
// for(i = 2; (i * i) <= number; i++)
for(i = 2; i <= number/i; i++)
A good compiler will see the nearby number%i and number/i and emit efficient code for the two of them, thus not incurring an expensive 2nd operation.
The below also overflows when upper_limit == INT_MAX
for(i = lower_limit; i <= upper_limit; i++)
Perhaps
for(i = lower_limit; i - 1 < upper_limit; i++)
OK as long as lower_limit > INT_MIN.
I'm trying to finish my homework, while there is something trapped me.
Here the question:
In the range of N, output those numbers whose factors sum is equal to themselves according to the following format.
Input:
1000
output:
6 its factors are 1 2 3
28 its factors are 1 2 4 7 14
496 its factors are 1 2 4 8 16 31 62 124 248
Here my code, please tell me why can't i get the right output. Appreciate it if
you can improve it for me.
Thanks in advance.
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int N;
scanf("%d",&N);
getchar();
for(int p=2;p<N;p++)//1 and N are not included.
{
int j=0,sum=0;
for(int i=1;i<p; )
{
//get factors and put them into array.
while(p%i==0)
{
goal[j]=i;
sum+=goal[j];
j++;
i++;
}
}
//judge the sum of factors and p the two values are equal.
if(sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
while(i==j-1)
printf("%d \n",goal[i]);
}
}
}
return 0;
}
Making the same a little clean,
int main()
{
int N, factors_sum, factors_cnt, num, j;
scanf("%d", &N);
int *factors = malloc(sizeof(int) * N/2);
if (factors == NULL)
{
perror("malloc(2)");
return 1;
}
for (num = 2 ; num < N ; ++num)
{
factors_cnt = 0;
factors_sum = 0;
for (j = 1 ; j <= num/2 ; ++j)
if (num % j == 0)
factors_sum += (factors[factors_cnt++] = j);
if (factors_sum == num)
{
printf("%d its factors are", num);
for (j = 0 ; j < factors_cnt ; ++j)
printf(" %d", factors[j]);
printf("\n");
}
}
free(factors);
return 0;
}
Modifications retaining your code:
#include<stdio.h>
#define NUM 100
int main()
{
int goal[NUM];//array for factors.
int sum=0;
int N;
scanf("%d",&N);
//getchar(); // I donno why you need this, better to remove it
for(int p=2;p<N;p++)//1 and N are not included.
{
// sum is different for every number
// need to be set to 0 individually for every number
sum = 0;
int j=0;
for(int i=1;i<p; i++) // i++ everytime
{
//get factors and put them into array.
if (p%i==0)
// changed while to if
// while would keep executing forever
{
goal[j]=i;
sum+=goal[j];
j++;
}
}
//judge the sum of factors and p the two values are equal.
if (sum==p)
{
printf("%d its factors are ",p);
for(int i=0;i<j;i++)
{
// no need for while here
printf("%d \n",goal[i]);
}
}
}
return 0;
}
I have made modifications in your code and corrected/commented where you have made mistakes.
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;
}
Hi I have this code here
int calMode(RECORD list[], int count)
{
int tempMode = 1;
int i = 1, j, k;
int current = 0;
while ( i <= count)
{
k = 1;
if (list[current].score == list[current + i].score)
{
k++;
i++;
}
printf("%d:", list[current].score);
for(j = 0; j <= k ; j++)
{
printf("*");
}
printf("\n");
current = current + k;
i++;
}
return tempMode;
}
I thought the logic of the code is ok, why is it going into an infinite loop ?
can anyone suggest a way to fix this code? and the list of data is assume to be sorted before going into the function calMode, I think there is a problem at the for loop
I edited the code know my out put is
60
66
71
71
72
75
79
82
82
82
91
size is: 12
73.50
60:**
66:*
71:*
71:*
72:*
75:*
79:*
82:*
82:*
82:*
91:*
The output is wrong but it is no longer in infinite loop
if (list[current].score == list[i].score)
{
k++;
i++;
}
If this test is wrong, i will never be incremented and here is the infinite loop.
FIX E.g.
int calMode(RECORD list[], int count){
int tempMode = 1;
int i, k;
int current = 0;
while (current < count){
printf("%d:", list[current].score);
for(k=0; (i=current + k) < count ; ++k){
if(list[current].score == list[i].score)
printf("*");
else
break;
}
printf("\n");
current = current + k;
}
return tempMode;
}
According to your code, if the scores of 0 th elemennt and 1st element are not equal, it will end up in infinite loop. I think some increment condition should be outside if statement too. [I dont know your logic, this is just a guess]