static void prime ( int number ){
for(int i = 3; i <= number; i++){
int r = 0;
for( int j = 2; j <= i - 1; j++){
r = i % j;
if( r == 0 ) {
break;
}
else
r = i % j;
}
if( r != 0 )
System.out.println(i + " is prime");
}
}
Any ideas how to incorporate values 1 and 2?Pinto wrote::) Absolutely, but I was thinking if I can actually put them in the calculations somehow. But maybe it'll be just easier with the print statements.
Since 1 is not prime and 2 is, you could just cheat and have two separate print statements for them before going into the loop for the rest of the numbers.
You can make it many times as fast by changing that to:j <= i - 1
j*j < i
Do you understand why? EJP wrote:That fails for 3. Better and more common approach is j less than or equal to square root of iYou can make it many times as fast by changing that to:j <= i - 1
Do you understand why?j*j < i
Better and more common approach is j less than or equal to square root of iPlease explain analytically the difference between
j*j < i
and j < Math.sqrt(i)
and please enumerate one or more cases for which they yield different results. EJP wrote:No. Can you, please explain?You can make it many times as fast by changing that to:j <= i - 1
Do you understand why?j*j < i
blias wrote:I want to find the factors of 36:EJP wrote:No. Can you, please explain?You can make it many times as fast by changing that to:j <= i - 1
Do you understand why?j*j < i
1 2 3 4 6 9 12 18 36
x
36 18 12 9 6 4 3 2 1
See how once I hit 6--that is, the square root of 36--everything starts repeating? By the time I hit the sqrt, I have found all the factors. So by the time I hit the sqrt of some number, if I haven't found any factors other than that number and 1, there aren't any, so it's prime.static void factors ( int number ){
StringBuilder sb = new StringBuilder();
StringBuilder sb1 = new StringBuilder();
int r = 0;
for( int i = 1; i < Math.sqrt(number); i++){
if(number % i == 0){
r = number / i;
if( sb.length() != 0 )
sb.insert(sb.length(), " ,");
sb.insert(sb.length(), r);
if( sb1.length() != 0 )
sb1.insert(sb1.length(), " ,");
sb1.insert(sb1.length(), i);
}
}
System.out.println(number + " has factors " + sb + " ," + sb1);
}
If I get 36 as an example the program misses the sqrt value itself. I understand it is because for( int i = 1; i < Math.sqrt(number); i++)
but if I change i <= Math.sqrt(number;
I get the value displayed twice.i < Math.sqrt(number)
I recommend you follow EJP's suggestion and use i * i <= number
That will be faster, and keep you in the realm of integers. (Though it will mean you'll have a smaller range you can work with before you have to upgrade to long or BigInteger).