2011年3月28日 星期一

Java 因數分解


import java.util.Scanner;

public class Factorization {
   public static void main(String[] args){
      Scanner sc = new Scanner(System.in);
      StringBuffer str;
      Boolean zero;
      long a ;
      int b, index;
      String ss = "S";

      while(sc.hasNext()){
        zero = false;
        str = new StringBuffer();
        a = sc.nextLong();
        b = (int)Math.sqrt(a) + 1;
   
        for(long i = 2; i <= b; i++){
            int c = 0;
            if(a == 2){
               str.append(a + " * ");
               break;
            }
            for(long j = i; j <= b; j *= (zero == true ? i : 1)){
                if( a % j == 0){
                   str.append(j);
                   str.append(" * ");
                   a /= j;
                   c++;
                   ss = Long.toString(j) + " * ";
                   zero = false;
                }
                else{
                   if( c >= 2){
                      str.delete(str.indexOf(Long.toString(j)),str.lastIndexOf("*")+2);
                      str.append(Long.toString(j) + "^" + Integer.toString(c) + " * ");
                   }
                   c = 0;
                   zero = true;
                }
            }
        }
        index = str.length();

        if(index == 0){
            str.append(a);
        }
        else{
            if(ss.equals(str.toString()) == true){
               str.append(" * " + a);
            }
            str.delete(index-3,index);
        }
        System.out.println(str);
      }
   }
}

沒有留言:

張貼留言