SelfDivisor
is #1 from the from the 2007 AP Computer Science A Free Response problems.
Part (a) isSelfDivisor
method
public static boolean isSelfDivisor(int number)
{
if(number == 0)
return false;
int numRemaining = number;
while(numRemaining > 0)
{
int digit = numRemaining % 10;
if(digit == 0 || number % digit != 0)
return false;
numRemaining /= 10;
}
return true;
}
See Division operations for discussion of using integer division (/
) and modular division (%
).
Part (b) firstNumSelfDivisors
method
public static int[] firstNumSelfDivisors(int start, int num)
{
int[] selfDivisors = new int[num];
int possible = start;
int i = 0;
while(i < selfDivisors.length)
{
if(isSelfDivisor(possible))
{
selfDivisors[i] = possible;
i++;
}
possible++;
}
return selfDivisors;
}
2007 AP CS Exam Free Response Solutions
Help & comments
Get help from AP CS Tutor Brandon Horn