这是我在编写一个java应用程序时的尝试(和失败),该应用程序显示仅在1到100之间的整数范围内复合的整数
//打印出1到100之间复合数字的java应用程序
>//public class printcomposites{
>//main exceutes java application
>public static void main(String[] args){
>//loop to iterate all candidate values from 1 through 100
>for( int i = 1 ; i <=99 ; i++ )
>{
> // a nested loop to define the divisors of the candidate values
>// what should ?? be for an efficient program?
>for ( int j = 1 ; j <= i ; j++ )``
>{
> // a statement to identify composite numbers from the candidate value
>if ( i%j==0 )
>{
>// collect or display the identified composite numbers
>j=j+i;
>System.out.printf("%d\t",j);
>}//end if
> }//end
我的代码显示1-100中的所有整数,而不是仅为复合整数的整数。我哪里出错了
答案 0 :(得分:1)
一些事情:
你应该有类似的东西:
for (int i = 3; i <= 99; i++) {
for (int j = 2; j <= i/2; j++) {
if (i % j == 0) {
System.out.println(i);
break;
}// end if
}
}
答案 1 :(得分:0)
这里有一些问题。
以下是它的样子:
public static void main(String[] args){
for( int i = 2 ; i <=99 ; i++ ) //iterate 1 - 99; 2 is prime
{
for ( int j = 2 ; j < i ; j++ ) //iterate 2 - potential composite EXCLUSIVELY; every number can be divided by one and itself
{
if (i%j==0 ) //test to see if the given number less than i is a factor of i
{
System.out.println(i); //i is a composite, because it has a factor, j. Print it.
break; //we already know it's a composite, no need to keep testing
}
}
}
}