Reputation: 341
Why my if statement is not working as desired- if((l1 % PrimeArr[l2]) == 0). Below is what I have coded-
/* Find all prime numbers<=N */
# include<stdio.h>
#define SIZE 100
void main()
{
int PrimeArr[SIZE];
int number;
int primeIndex=2; // 2 for 2 and 3 in the array
int l1; // loop counter 1
int l2; // loop counter 2
int l3; // loop counter 3
// 1. 2 is the only even prime number, save this in PrimeArray
PrimeArr[0]=2;
// 2. 3 is first odd prime number, save this in PrimeArray too.
PrimeArr[1]=3;
// 3. ask user uptil which number he want primes.
printf("\n Enter your number:");
scanf("%d",&number);
// 4. for numbers 4 to N if number P is divisible by all prime numbers less than P
for(l1=4;l1<=number;l1++){
for(l2=0;l2<primeIndex;l2++)
{
// 4.1 if yes, then p is composite
if((l1 % PrimeArr[l2]) == 0)
break; /* found out that the number is composite so let's get out of this loop to avoid unnecessary division */
else
{
//4.2.1 save this prime in prime array
PrimeArr[primeIndex++]=l1;
}
}
}
// display your prime array.
for(l3=0;l3<primeIndex;l3++)
printf("%d ",PrimeArr[l3]);
}
Basically when it reaches the inner loop, the if is being ignored. What I want to do is- " break the current loop if the number is divisible by any prime number available in the array" but it is being ignored always and the control is going in the else always.
Upvotes: 0
Views: 85
Reputation: 429
Your approach for this problem is flawed. In the nested for loop you're only checking if a number is an even number or not and if it's not you're categorizing it as a prime number which is not right obviously(e.g.9,15, etc are not prime).
Now, what you should is, you should check until that number's half that is it divisible or not.
for(i=2; i<=number/2; ++i)
{
// condition for nonprime number
if(number%i==0)
{
flag=1;
break;
}
}
if (flag==0)
PrimeArr[primeIndex++] = number;
Try this inside your outer for loop. Do remember to declare flag and i etc.
Upvotes: 1