## Program to find practical numbers

In number theory, a **practical number** or **panarithmic number** is a positive integer *n* such that all smaller positive integers can be represented as sums of distinct divisors of *n*. For example, 12 is a practical number because all the numbers from 1 to 11 can be expressed as sums of its divisors 1, 2, 3, 4, and 6: as well as these divisors themselves, we have 5=3+2, 7=6+1, 8=6+2, 9=6+3, 10=6+3+1, and 11=6+3+2.

The sequence of practical numbers

- 1, 2, 4, 6, 8, 12, 16, 18, 20, 24, 28, 30, 32, 36, 40, 42, 48, 54, ….

Here is the Java code to find practical numbers in between given sequence.

/** * * @author Vasanth Raja Chittampally */ public class PracticalNumbers { public int[] getPracticalNumbers(int from, int to) { int a[]=new int[to-from]; int indx=0; out:for (int i = from; i<=to;i++) { int sum=0; for(int j=1;j<=i/2;j++) { if(i%j==0) { if(sum<j-1) continue out; sum+=j; } } if(sum>=i-1) { a[indx++]=i; } } int count=0; for (int i = 0; i < a.length; i++) { if(a[i]!=0) count++; } int ans[]=new int[count]; for (int i = 0; i <count; i++) { ans[i]=a[i]; } return ans; } // You could use this sample code to test function // Following main fucntion contains 3 representative test cases public static void main(String[] arg) { PracticalNumbers pn = new PracticalNumbers(); //1st test case int[] res = pn.getPracticalNumbers(1, 20); for (int i = 0; i < res.length; i++) System.out.print(res[i] + " "); System.out.println(); //2nd test case int[] res2 = pn.getPracticalNumbers(8000, 8200); for (int i = 0; i < res2.length; i++) System.out.print(res2[i] + " "); System.out.println(); //3rd test case int[] res3 = pn.getPracticalNumbers(1000, 1120); for (int i = 0; i < res3.length; i++) System.out.print(res3[i] + " "); System.out.println(); } }

Here is the online ide where you can see the output

I feel the above program is self explanatory. If you have any doubts at any line please leave a comment. I’ll clarify your doubts. Thank you. I always welcome your comments or suggestions.

hey, nice concept.. but there is a bug:-) where is the sum being updated in the getPracticalNumber method?

Thanks yar… I must apologize for that mistake.. Actually the problem is with the

Sorry for not showing the indentation.. It is removing some of the statements if I use indentation. Here I’m sharing ideone online compiler you can click and see the output.

http://ideone.com/4nkaV

its fixed master:-) perfect..