114k views
3 votes
Consider the task of writing a method named countFactors that accepts an integer (assumed to be positive) as its parameter and returns a count of its positive factors. For example, the six factors of 12 are 1, 2, 3, 4, 6, and 12, so the call countFactors(12) should return 6. The following is an attempt at solving the problem, but it is incorrect. Determine what is wrong with the code, and submit a corrected version that works properly.public static int countFactors(int n) {

for (int i = 1; i <= n; i++) {
if (n % i == 0) { // a factor
return i;
}
}
}

1 Answer

6 votes

Answer:

Instead of return i in the if you should store i in an array or print i.

Step-by-step explanation:

In the code there is written return i.As the compiler encounter the return statement the execution of the function stops it returns the value that i.That we don't want to do.This code will return only 1 factor that is 1.You can either print the factor for that inn the if statement instead of return print the values of i.Since the function is of integer type return 0 in the end or you can create an array and an integer with initial value 0 and insert all i's in if statement in the array.

User Daemontus
by
6.4k points