+ 1

By using for loop how i printed prime numbers?

11th Mar 2017, 4:33 AM
abdifatah said Salad
abdifatah said Salad - avatar
4 Respuestas
+ 12
for(i=0;i<n;i++) { count=0; for(j=1;j<=i;j++) { if(i%j==0) { count++; } } if(count==1&&count==2) { // print i } } // this will print all the prime number between limit i.e.,0 to n numbers
11th Mar 2017, 11:04 AM
Mansi Dagla
Mansi Dagla - avatar
+ 8
The iteration limit to find prime numbers can be square root of the tested number, instead its half: x = sqrt( x ) * sqrt( x ), so, all x values greater than sqrt( x ) were already tested, by testing divisors lighter than x ^^
12th Mar 2017, 7:58 AM
visph
visph - avatar
+ 1
int numDiv = 0; int max = 2947; //max serves as a limit for how many primes, highest number you want to test. for(int x = 0; x < max; x++){ numDiv = 0; for(int y = 2; y <= x/2; y++){ //tests divisors of x //prime numbers have no divisiors other than 1 and themselves if(x%y == 0){ numDiv++; } } if(numDiv == 0){ System.out.println(x + " is prime"); } }
11th Mar 2017, 5:27 AM
Michael Szczepanski
Michael Szczepanski - avatar
+ 1
Abdul, having your for loop to x < n, is a waste of computational time. the lowest number that a non prime can be divisible by is 2, therefore the highest divisor would be n/2. testing any case over the half way point is a wast of time and processing power. what if you were trying to determine if a Large number was prime. you wouldn't want to look at twice the numbers you dont need to. think about that.
11th Mar 2017, 7:04 AM
Michael Szczepanski
Michael Szczepanski - avatar