# Write program to check if an integer is divisible by 2, 3 and 5 [closed]

Write a program to check if an integer is divisible by either 2, 3 or 5. If an integer is divisible more than one of these numbers it should also show all of them.

For example:

• 8 is divisible by only 2
• 10 is divisible by 2 and 5
• 30 is divisible by 2, 3 and 5
• Check out Divisors and Divisible. – corey979 Nov 4 '16 at 21:31
• If an number is divisible by "2, 3 &5", then it is divisible by all three of them, and therefore it is divisible by more than one. Perhaps you meant "or", not "&"? The example, while a true statement, seems pointless, since it does not indicate what the output should be in each case. – Michael E2 Nov 4 '16 at 22:15
• What output is specified for inputs divisible by none of 2, 3, 5? – Eric Towers Nov 6 '16 at 16:30
• I'm voting to close this question as off-topic because this is not a "code my homework" site. – Daniel Lichtblau Nov 6 '16 at 19:26

f[x_]:=Intersection[Divisors[x],{2,3,5}]

f


{2, 3, 5}

f


{2, 5}

f


{3}

More general:

g[x_, divisors_List]:=Intersection[Divisors[x],divisors]

g[25, {2, 3, 5}]


{5}

If[1!=GCD[n, 2 3 5],FactorInteger[GCD[n, 2 3 5]][[All, 1]]]

• Why the If? There's no specification what to output for relatively prime inputs. Also, if we're golfing ... If[1!=#,FactorInteger[#][[All, 1]]]&@GCD[n, 30]. – Eric Towers Nov 5 '16 at 15:41
• @EricTowers, with relatively prime inputs, nothing is output. – Fred Kline Nov 6 '16 at 2:22
• I see no specification for that conclusion. I only see specification for divisible inputs. – Eric Towers Nov 6 '16 at 16:30

Also note that you can use the rightmost digit for 2 and 5 - eg: [2,4,6,8,0] for 2 amd [0,5] for 5.

With 3 this gets a little bit lengthy. A different approach is to sum all the digits repeaatdly until the final 1 digit number is that of 0, 3, 6, 9. eg: 342 is 3+4+2 = 9 so it's divisible by 3.

Code left for reader but on smaller processors without a divide op these can drastically speed up the checks.

• I actually think this is a good point, but an answer without code, is not an answer. – Feyre Nov 5 '16 at 15:22
• As far as I can tell, this is not faster, in fact it's about 2 times slower than the most upvoted answer. – Feyre Nov 5 '16 at 15:32
• As I said it depends on the processor. – Craig Taylor Nov 5 '16 at 15:36
• Feyre - Not high enough level yet to post as a comment. – Craig Taylor Nov 5 '16 at 16:06
• I would upvote this as an answer if you fix the typos and add Mma code to carry out the checks you suggest. Welcome to the Mathematica Stack Exchange. – dionys Nov 5 '16 at 16:17