By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,872 Members | 2,392 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,872 IT Pros & Developers. It's quick & easy.

want to know the complexity of my program ,new way to find prime numbers

P: 1
//simply we are going to use the approach that the numbers that are divisble by prime numbers are not prime and the others are prime.
#include<stdio.h>
#include<math.h>
int main()
{
int n,i,arr[100000],size=0,j,temp; // array is for storing prime numbers
scanf("%d",&n); // we will be finding prime numbers between 2 to n (both inclusive)
arr[0]=2; // we know that 2 is a prime number
size++; // we got 1 prime number so size of array gets incremented
for(i=3;i<=n;i++)
{
temp=pow(i,0.5); //square root of the number (for which we are going to check is it prime or not)
for(j=0;arr[j]<=temp;j++){
if(i%arr[j]==0)
break;
}
if(arr[j]>temp)
{
arr[size]=i;
size++;
}
}
for(i=0;i<size;i++)
printf("%d \n",arr[i]);
return 0;
}
Apr 23 '17 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
I don't think your algorithm works.

Prime numbers are numbers that are the product of themselves and 1. Saying it another way, the only factors of a prime number are the prime number itself and 1. Nothing about division, square roots, etc.

The code says:
Expand|Select|Wrap|Line Numbers
  1. //simply we are going to use the approach that the numbers that are divisble by prime numbers are not prime and the others are prime.
All numbers are divisible by prime numbers since all numbers are divisible by 1. All even numbers are divisible by 2.

You have to write a loop that tests a given number to be prime. It would divide the number by all numbers from 2 to the number itself. The number is prime if the only non-zero quotient is 1 by using the number itself.
Apr 23 '17 #2

Expert 100+
P: 2,398
I suggest you look at The Sieve of Erasthones. It is a method for accomplishing your goal that doesn't require any division.
Apr 24 '17 #3

Post your reply

Sign in to post your reply or Sign up for a free account.