4.12. Free Response - Self Divisor A

The following is part a of a free response question from 2007. It was question 1 on the exam. You can see all the free response questions from past exams at https://apstudents.collegeboard.org/courses/ap-computer-science-a/free-response-questions-by-year.

Question 1. A positive integer is called a “self-divisor” if every decimal digit of the number is a divisor of the number, that is, the number is evenly divisible by each and every one of its digits. For example, the number 128 is a self- divisor because it is evenly divisible by 1, 2, and 8. However, 26 is not a self-divisor because it is not evenly divisible by the digit 6. Note that 0 is not considered to be a divisor of any number, so any number containing a 0 digit is NOT a self-divisor. There are infinitely many self-divisors.

Part a. Finish writing method isSelfDivisor below, which takes a positive integer as its parameter. This method returns true if the number is a self-divisor; otherwise, it returns false. The main method includes tests to check if this method is working correctly.

public class SelfDivisor
{

   /** @param number the number to be tested
    *         Precondition: number > 0
    *  @return true if every decimal digit of
    *          number is a divisor of number;
    *          false otherwise
    */
   public static boolean isSelfDivisor(int number)
   {
     // part A
   }

   /****************/

   public static void main (String[] args)
   {
     System.out.println("128: " + isSelfDivisor(128));
     System.out.println("26: " + isSelfDivisor(26));
     System.out.println("120: " + isSelfDivisor(120));
     System.out.println("102: " + isSelfDivisor(102));
   }
 }

4.12.1. How to solve this problem

The first thing to do is try to solve the examples by hand. The question tells us that 128 should return true, 26 should return false, and any number with a 0 in it should return false.

To check if 128 is a self-divisor we divide 128 by 8, 2, and 1. If 8, 2, and 1 each go into 128 evenly (have a 0 remainder) then the method should return true.

To check if 26 is a self-divisor we divide 26 by 6 and find that it has a remainder that is greater than 0, so it can’t be a self-divisor and we return false.

To return false if the number has a 0 in it we just have to check if the current digit is a zero and then return false. So, 120 and 102 should both return false.

Click to reveal hints and problems to lead you to the solution or skip ahead to write your own solution.

Try to write the code for the method isSelfDivisor. When you are ready click “Run” to test your solution. Remember that it should return true for 128, false for 26, false for 120, and false for 102.

FRQ SelfDivisor: Write the method isSelfDivisor.

4.12.2. Video - One way to code the solution

There are many possible solutions to this problem. Click to reveal a possible solution’s video for this problem.

You have attempted of activities on this page