+ 1
Please someone explain me how to print prime numbers up to given number using java..
3 Answers
+ 4
A prime number is something that is positive and is only divisible by 1 and itself, where itself =/= 1.
You can find divisibility with the modular operator.
Denoted, %.
If a number, x, mod another number, a, is equal to 0, it is divisble by that number, a.
So, if x is the number we're checking for prime,
and a is the number we're checking for divisibility, starting at 2 up to (but excluding) x.
if(x % a == 0)
// then number is not a prime.
There's many ways to optimize this, but that's the easiest method. Keep in mind no optimizations is not practical for real use.
+ 1
public class Program
{
public static void main(String[] args) {
int count;
for(int i=2;i<=30;i++){
count=0;
for(int j=2;j<i;j++){
if(i%j==0){
count++;
break;
}
}
if(count==0){
System.out.println(i);
}
}
}
}
//this is the code I wrote for prime numbers up to 30