这是一个家庭作业问题。
代码编译,但在测试用例中,2输出完美,而不是。
我无法使用数组。我无法使用Math.min()
或Math.max()
。纯粹的条件和循环。
我的教授说我只需要测试除了n / 2之外的除数,但是当我这样做时,我仍然得到2作为完美数字。
任何帮助将不胜感激。
// Project2.java
import java.io.*; // BufferedReader
import java.util.*; // Scanner
public class Project2
{
public static void main (String args[]) throws Exception
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED CMD ARGS
if (args.length < 3)
{
System.out.println("\nusage: C:\\> java Project2 <input file name> <lo> <hi>\n\n");
// i.e. C:\> java Project2 P2input.txt 1 30
System.exit(0);
}
String infileName = args[0]; // i.e. L2input.txt
int lo = Integer.parseInt( args[1] ); // i.e. 1
int hi = Integer.parseInt( args[2] ); // i.e. 30
// STEP #1: OPEN THE INPUT FILE AND COMPUTE THE MIN AND MAX. NO OUTPUT STATMENTS ALLOWED
Scanner infile = new Scanner( new File(infileName) );
int min,max;
min=max=infile.nextInt(); // WE ASSUME INPUT FILE HAS AT LEAST ONE VALUE
while ( infile.hasNextInt() )
{
// YOUR CODE HERE FIND THE MIN AND MAX VALUES OF THE FILE
// USING THE LEAST POSSIBLE NUMBER OF COMPARISONS
// ASSIGN CORRECT VALUES INTO min & max INTHIS LOOP.
// MY CODE BELOW WILL FORMAT THEM TO THE SCREEN
// DO NOT WRITE ANY OUTPUT TO THE SCREEN
int number = infile.nextInt();
if ( number < min )
{
min = number;
}
else if ( number > max )
{
max = number;
}
}
System.out.format("min: %d max: %d\n",min,max); // DO NOT REMOVE OR MODIFY IN ANY WAY
// STEP #2: DO NOT MODIFY THIS BLOCK
// TEST EVERY NUMBER BETWEEN LO AND HI INCLUSIVE FOR
// BEING PRIME AND/OR BEING PERFECT
for ( int i=lo ; i<=hi ; ++i)
{
System.out.print( i );
if ( isPrime(i) ) System.out.print( " prime ");
if ( isPerfect(i) ) System.out.print( " perfect ");
System.out.println();
}
} // END MAIN
// *************** YOU FILL IN THE METHODS BELOW **********************
// RETURNs true if and only if the number passed in is perfect
static boolean isPerfect( int n )
{
int sum = 0;
for(int i = 1; i <= n/2; i ++)
{
if(n%i == 0)
{
sum += i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
// (just to make it compile) YOU CHANGE AS NEEDED
}
// RETURNs true if and only if the number passed in is prime
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
for(int i = 2; i <= n/2; i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}// (just to make it compile) YOU CHANGE AS NEEDED
}
答案 0 :(得分:0)
好的,我发现了一个错误,虽然它不是你描述的错误。
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
这会错误地将2列为非素数,因为它小于3。