Reputation: 3
I'm trying to print the following series 4 6 12 18 30 42 60 72....up to n in C language. Its logic is simple; we have to print the number such that the preceding and successive number should be prime! But the following code is not looping after printing the 4. What's wrong in the following code?
#include <stdio.h>
int main(){
int n, i, j, p2, k;
int count1=0, count2=0;
printf("enter the number:\n");
scanf("%d",&n);
for(i=3;i<n;i++){
for(j=2;j<i;j++){
if(i%j==0){
count1++;
break;
}
}
p2=i+2;
for(k=2;k<i;k++){
if(p2%k==0){
count2++;
break;
}
}
if(count1==0 && count2==0){
printf("%d",i+1);
}
}
}
Upvotes: 0
Views: 2938
Reputation: 1
your code is right, just set count1 and count2 to 0 at the end of the outer for loop.
you can try it this way too.
this code is in Java. you can convert it to C . Logic remains the same.
for Arraylist
take arrays of fixed length equal to n
.
import java.util.*;
class prime
{
public static void main(String[] args){
int n, i, j, p2, k,o;
ArrayList<Integer> prime = new ArrayList<Integer>();
ArrayList<Integer> series = new ArrayList<Integer>();
int count1=0, count2=0;
Scanner s = new Scanner(System.in);
System.out.println("enter the number:\n");
n=s.nextInt();
if(n<3)
{
System.out.println("prime numbers start from 3");
}
for(i=3;i<=n;i++)
{
for(j=2;j<i;j++)
{
if(i%j==0)
{
count1=1;
break;
}
}
if(count1==0)
{
prime.add(i);
}
count1=0;
}
for(k=0;k<prime.size()-1;k++)
{
int prdsr=prime.get(k);
int sucsr=prime.get(k+1);
if((sucsr-prdsr)==2)
{
series.add((prdsr+1));
}
}
for(o=0;o<series.size();o++)
{
System.out.print(" "+series.get(o));
}
}
}
Upvotes: 0
Reputation: 78
You just need to set counters to 0 at the end of the loop
#include<stdio.h>
int main(){
int n, i, j, p2, k;
int count1=0, count2=0;
printf("enter the number:\n");
scanf("%d",&n);
for(i=3;i<n;i++){
for(j=2;j<i;j++){
if(i%j==0){
count1++;
break;
}
}
p2=i+2;
for(k=2;k<i;k++){
if(p2%k==0){
count2++;
break;
}
}
if(count1==0 && count2==0){
printf("%d ",i+1);
}
count1=0; count2=0;
}
}
Upvotes: 1