Zakir - 7 months ago 12

Java Question

To determine if a number is divisible by 7, take the last digit off the number, double it and subtract the doubled number from the remaining number. If the result is evenly divisible by 7 (e.g. 14, 7, 0, -7, etc.), then the number is divisible by seven. This may need to be repeated several times.

Example: Is 3101 evenly divisible by 7?

`310 - take off the last digit of the number which was 1`

-2 - double the removed digit and subtract it

308 - repeat the process by taking off the 8

-16 - and doubling it to get 16 which is subtracted

14 - the result is 14 which is a multiple of 7

The following is the code that I did to get the number:

`for(int O =0; O <= 9 ; O++) {`

String a = String.valueOf(number[0]);

String b = String.valueOf(number[1]);

String c = String.valueOf(number[2]);

String d = String.valueOf(number[3]);

String e = String.valueOf(number[4]);

String f = String.valueOf(number[5]);

String h = a+b+c+d+e+f;

int abcdef = Integer.valueOf(h);

if ( (abcdef -(2*O) % 7) ==0 )

number [6] = O;

}

However, it is not giving me a number of such kind.I was able to get a number up until 6 where up until each digit the number is divisible by the respective index(if I start with 1, not 0 for the index).Which means index 1 is divisible by 1, index 2 is divisible by 2, index 3 is divisible by 3,......index 7 is divisible by 7.I want to form a number of such kind.Note that I could have done it without using the algorithm by the following way:

`for(int O =0; O <= 9 ; O++) {`

String a = String.valueOf(number[0]);

String b = String.valueOf(number[1]);

String c = String.valueOf(number[2]);

String d = String.valueOf(number[3]);

String e = String.valueOf(number[4]);

String f = String.valueOf(number[5]);

String g = String.valueOf(O);

String h = a+b+c+d+e+f+g;

int abcdefg = Integer.valueOf(h);

if ( (abcdefg % 7) ==0 )

number [6] = O;

}

However, I really want to do it using the algorithm that I described in the beginning.

Answer

Here is a recursive solution:

```
public static boolean isDivisibleBy7 (int n)
{
System.out.println("Checking " + n);
if (n == 0 || n == 7 || n == 14)
{
return true;
}
else if (n < 0)
{
return false;
}
else
{
int lastDigit = n % 10;
int lastDigitOff = n / 10;
return isDivisibleBy7(lastDigitOff - (lastDigit * 2));
}
}
```

Source (Stackoverflow)

Comments