Novice C language learning journey(2)

sky-999(43)
Published in
#art
Words
47
Reading
1 min
Listen
Play
7y

梦幻光晕蓝色背景矢量图.png
This is a code of to solve the prime numbers.
But it has a problem,the print results is not prime numbers entirely.And it print many repeat numbers.The code as follows:
#include"math.h"
#include"stdio.h"
int main(void){

int i,j,a,n;
n=0;
for(i=101;i<200;i+=2){   
    if(n%10==0)
        printf("\n");
    j=sqrt(i);
    for(a=2;a<=j;a++)
        if(i%a==0)
            break;
    else {       
        printf("%d  ",i);
        n++;
    }
}
return 0;

}
捕获1.PNG
But no long after.I found the reason.the problem is this statement of "else".
"i" variable can be devisible by some "a" variable when a<=j.But the statement is "else" in the following statement.So it print i variable in console.But the value of i variable at the moment is not a prime numbers.So the modified code is as follows:
#include"math.h"
#include"stdio.h"
int main(void){

int i,j,a,n;
n=0;
for(i=101;i<200;i+=2){   
    if(n%10==0)
        printf("\n");
    j=sqrt(i);
    for(a=2;a<=j;a++)
        if(i%a==0)
            break;
    if(a>j) {       
        printf("%d  ",i);
        n++;
    }
}
return 0;

}
捕获.PNG

Novice C language learning journey(2) | Ecency