Reputation:
I'm newly new to C programming , started about a week ago ! And i'm getting into loops i faced a problem writing a C program to show prime numbers less-than 100 . I'll share up the C code i've written and its output ! I'll wait for your help and your remarks about it
#include<stdio.h>
main(){
int i,d,k;
for( i=1 ; i<=100 ; i++ ){
d=0;
for( k=1 ; k<=i ; k++ ){
if( i%k==0){
d=d+1;
}
}
if( d==1 ){
printf("\n%d",i);
}
}
getchar();
getchar();
}
Output:
1
Thanx !
Upvotes: 2
Views: 4873
Reputation: 376
#include<stdio.h>
main(){
int i,d,k;
for( i=1 ; i<=100 ; i++ ){
d=0;
for( k=1 ; k<=i ; k++ ){
if( i%k==0){
d=d+1;
}
}
if( d==1 ){
printf("\n%d",i);
}
}
getchar();
}
Upvotes: 1
Reputation: 452
Here you go...e.g 5 has to factors (1 and 5):
#include<stdio.h>
main(){
int i,d,k;
for( i=1 ; i<=100 ; i++ ){
d=0;
for( k=1 ; k<=i ; k++ ){
if( i%k==0){
d=d+1;
}
}
if( d==2 ){
printf("\n%d",i);
}
}
getchar();
getchar();
}
Upvotes: 2
Reputation: 5110
You are using d
as a flag
to detect if number was ever divisible during the inner for loop. Use it right. Whenever no is divisible, set flag to 1 indicating it's not prime. If flag is unaffected through the inner loop, means number is prime. You should also consider returning an int
value from main
function indicating exit status.
Change the code as follows.
#include<stdio.h>
main(){
int i,d,k;
for( i=2 ; i<=100 ; i++ ){
d=0;
for( k=2 ; k<i ; k++ ){
if( i%k==0){
d=1; //Set the flag to 1 indicating no. is not prime and break
break;
}
}
if( d==0){ //Means flag the was unaffected throughout the loop i.i. Prime
printf("\n%d",i);
}
}
getchar();
return 0;
}
Upvotes: 0
Reputation: 9062
The main function should return an int: What should main() return in C and C++?.
Also, consider making a function to test if a number is prime. This is a cleaner approach, but I guess you did not learned them yet.
The algorithm you are using is not efficient at all. There are many ways to improve it.
To correct it, you should know that a prime number has 2 divisors (except 1, but it is not a prime): 1 and itself. Your second for loop checks for those 2, so a number is prime if d is 2, not 1.
Even if you are a beginner, you should try to improve this algorithm. Firstly, it is enough to check until sqrt(i) for divisors. Also, when you find a divisor, you can stop the loop. Also, as 1 is always a divisor, you may start the second loop with 2.
Upvotes: 0
Reputation: 9817
Reading your algorithm with i=2.
d=0
k=1 : 2%1=0 so d=1
k=2 : 2%1=0 so d=2
So 2 is not prime...Alrggg
There are many way to correct and make your code run faster. Computing sqrt(i) for all i might be "costly" if i<100, but doing something similar from time to time would be a good trick...
More : no need to continue once a divisor is found More : Eratosthenes is your friend... More : smaller divisor is always prime...Store ? More : look Wikipedia in fact... http://en.wikipedia.org/wiki/Primality_test Bye,
Francis
Upvotes: 0