Reputation: 19
I need help with this method smallestFactor
public static int smallestFactor(int C)
This function takes as its argument an integer C, and it returns the smallest integer that is a factor of C, other than 1.
Parameters: C - An integer to factor.
Precondition: C must be greater than 1.
Returns: The smallest factor of C.
public class Factor
{
public static long smallestFactor(int C)
{
for (int i = 2; i*i<= C; i++)
{
while (C % i == 0)
{
System.out.print(i + " ");
C = C / i;
}
}
return C;
}
}
I need to find the smallest Factor but I'm not sure how to do it
Upvotes: 1
Views: 5704
Reputation: 339856
The value you need to return is your i
, not C
.
You should work through possible values of i
in your loop, and return
that value when you find that C % i == 0
.
Note that for efficiency you should test 2, 3, and then every odd number thereafter. There's no point testing (4, 6, 8, ...) if you already tested 2:
public static int smallestFactor(int C) {
if (C % 2 == 0) return 2; // C is even
for (int i = 3; i * i <= C; i += 2) {
if (C % i == 0) return i; // odd factor found
}
return C; // no factor found
}
In fact the most efficient algorithm would only test for prime factors, but I suspect that's beyond the scope of what you've been asked.
Upvotes: 0
Reputation: 25950
Handling all exceptional cases, try this code:
public static long smallestFactor(int x)
{
if(x < 1) return -1;
if(x == 1) return 1;
for(int i=2; i<=x; i++)
if(x % i == 0)
return i;
return -1; // To stop compiler's complaints.
}
Upvotes: 0
Reputation: 34186
Small changes to your code- you were close!
public class Factor {
public static long smallestFactor(int C) {
for (int i = 2; i*i<= C; i++) {
if (C % i == 0) return i;
}
return -1;
}
}
Upvotes: 0
Reputation: 11866
You need to use if
instead of while
, and return i
if you find it.
public static long smallestFactor(int C)
{
for (int i = 2; i*i<= C; i++)
{
if (C % i == 0)
{
return i;
}
}
return C;
}
There are other improvements you could make, but that should get you started.
Upvotes: 5