Wednesday, March 9, 2016

Prime Factors in Java



 Write a Java program that is reading from the keyboard a value between 100 and 700 and is printing on the screen the divisors of the number.

Your program should use a cycle for validating the input (if the value typed from the keyboard is less than 100 or bigger than 700 to print an error and ask the user to input another value).

Also the program should print the prime factors in the order from smallest to biggest.

For example,

for the value 128 the program should print 128=2*2*2*2*2*2*2

for the value 122 the program should print: 122=2*61

change the program at a. to print one time a divisor but provide the power of that divisor:

for the value 128 the program should print 128=2^7

for the value 122 the program should print: 122=2^1*61^1



Solution Code:

import java.io.*;
import java.util.*;

public class Divisors {

  /* Java Program that is reading from the keyboard a value between 100 and 700
 and is printing on the screen the prime divisors of the number.  */
 public static void main(String args[]) throws IOException
 {
 List<Integer> resultList = new ArrayList<Integer>();
 Map<Integer, Integer> resultMap = new HashMap<Integer, Integer>();
 BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
 StringBuffer result = new StringBuffer();
 int n;
 System.out.print("Enter a Number : ");
 n=Integer.parseInt(br.readLine());
  if(n < 100 || n > 700)
  {
   System.out.println("Invalid Number!! Please enter the valid number in between 100 to 700");
  }
  else
  {
   System.out.print("The Prime Divisors of "+n+" are : ");
   int i=2;
   while(n>1)
   {
     if(n%i == 0)
     {
      resultList.add(i);
      //System.out.print(i+"*");
        n=n/i;
      }
   else
       i++;
   }  
   for(int index = 0; index < resultList.size(); index++)
   {
    if(index != resultList.size()-1)
     System.out.print(resultList.get(index)+"*");
    else 
     System.out.print(resultList.get(index));
    if(resultMap.containsKey(resultList.get(index)))
    {
     Integer value = resultMap.get(resultList.get(index));
     resultMap.put(resultList.get(index), value+1);
    }else
    {
    int initialize = 1;
    resultMap.put(resultList.get(index), initialize);
    }
   }
  System.out.println();
  Set<Integer> resultSet = resultMap.keySet();
  
  for(Integer key: resultSet)
  {
   result.append(key+"^"+resultMap.get(key)+"*");
  }
  
  result.replace(result.length()-1, result.length(), "");
  System.out.println(result);
   }
  }
}

No comments:

Post a Comment