Practical Numbers in Range

Last week i was breaking my head to get the solution for this Practical Number. In beginning it was taught to even understand what it is. Later i found the meaning of Practical Number from Wikipedia. My problem is to print list of practical number within a range. After some workout I got the solution to be like this,


 /**
 *
 * @author Prashant
 */

import java.util.*;
public class PracticalNumbers {
 public int[] getPracticalNumbers(int from, int to) {
 ArrayList<Integer> result = new ArrayList<Integer>();
 ArrayList<Integer> divisor = new ArrayList<Integer>();
 for(int i=from;i<=to;i++)
 {
 if(check4Practical(i))
 {
 result.add(i);
 }
 }
 int []res=new int[result.size()];
 for(int i=0;i<result.size();i++)
 {
 res[i]=result.get(i).intValue();
 }
 if(res.length>0)
 {
 return res;
 }
 return new int[]{};
 }
 boolean check4Practical(Integer num)
 {
 ArrayList<Integer> divisors = new ArrayList<Integer>();

 for(int i=1;i<num;i++){
 if(num%i == 0)
 {
 divisors.add(i);
 }
 }
 int[] divisors_arr = new int[divisors.size()];
 for(int i =0;i<divisors_arr.length;i++)
 {
 divisors_arr[i] = divisors.get(i).intValue();
 }
 for(int i = num-1;i>0;i--)
 {
 int temp = i;
 for(int j= divisors_arr.length-1;j>=0;j--)
 {
 if(temp>0)
 temp -= divisors_arr[j];
 if(temp <0)
 temp+= divisors_arr[j];
 if(temp == 0)
 break;
 }
 if(temp!= 0 )
 return false;
 }
 return true;
 }

 public static void main(String[] arg) {
 PracticalNumbers pn = new PracticalNumbers();
 //test case
 int[] res = pn.getPracticalNumbers(1, 200);
 for (int i = 0; i < res.length; i++)
 System.out.print(res[i] + " ");
 }
}

 
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: