Home > Programming > Program to find practical numbers

## 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&lt;=to;i++) {
int sum=0;
for(int j=1;j&lt;=i/2;j++) {
if(i%j==0) {
if(sum&lt;j-1)
continue out;
sum+=j;
}
}
if(sum&gt;=i-1) {
a[indx++]=i;
}
}
int count=0;
for (int i = 0; i &lt; a.length; i++) {
if(a[i]!=0)
count++;
}
int ans[]=new int[count];
for (int i = 0; i &lt;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 &lt; 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 &lt; 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 &lt; res3.length; i++)
System.out.print(res3[i] + " ");
System.out.println();
}
}
```

Here is the online ide where you can see the output

1. November 18, 2010 at 2:05 pm

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

• November 18, 2010 at 3:17 pm

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

` tag I used for having indentation.. Now I removed it..You can now see the correct code..`
2. November 18, 2010 at 3:23 pm

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

• November 18, 2010 at 4:23 pm

its fixed master:-) perfect..