1. 程式人生 > >JAVA-簡單面試題-演算法

JAVA-簡單面試題-演算法

2給一個正整數 n, 找到若干個完全平方數(比如1, 4, 9, ... )使得他們的和等於 n。你需要讓平方數的個數最少。

給出 n = 12, 返回 3 因為 12 = 4 + 4 + 4

給出 n = 13, 返回 2 因為 13 = 4 + 9

package Node_Swap;

import java.util.Scanner;



public class Search_Perfect_Square {
	
	
//	int the_start = (int) Math.sqrt(the_number);
	static int[] starts;
	static int[] starts_num;
	int counts = 0;
	public static void main(String[] args) {
		// TODO 自動生成的方法存根
		try{
		Scanner scan = new Scanner(System.in);
		System.out.println("請輸入正整數N:");
		int the_number = scan.nextInt();
		if(the_number ==0){
			System.out.println("0沒有完全平方數");
		}else if(the_number == 1){
			System.out.println("1");
		}
		else{
		int[] current_starts = new int[the_number];
		int[] current_starts_num = new int[the_number];
		int current_num = the_number;		
		int start = (int) Math.sqrt(the_number);
		while(start > 0){
			int i = 0;
			int counts_num = 0;
			starts = new int[the_number];
			starts_num = new int[the_number];
			Search_Perfect_Square sps = new Search_Perfect_Square();
			sps.Search_Perfect_Square(the_number,start);
			while(starts[i] > 0){
				counts_num += starts_num[i];
				i++;
			}
			if(current_num >= counts_num){
				current_num = counts_num;
				current_starts = starts;
				current_starts_num = starts_num;
			}
			start--;
		}

		output_square(current_starts,current_starts_num);
		}
		}catch(NegativeArraySizeException e){
			System.out.println("你輸入了錯誤的數!");
		}
		
	}
		
	public void Search_Perfect_Square(int the_start, int loop_start) {
		// TODO 自動生成的建構函式存根
	int the_other = 0;
	starts[counts] = loop_start*loop_start;
	starts_num[counts] = (int)the_start/(starts[counts]);
	the_other = the_start - starts[counts] * starts_num[counts];
	counts++;
	loop_start--;
	if(the_other == 0){
		counts = 0;
	}else{
		Search_Perfect_Square(the_other,loop_start);
	}
	}
	static void output_square(int[] output,int[] output_num){
		int i = 0;
		while(output[i]>0){			
			for(int j=0;j<output_num[i];j++){
				System.out.print(output[i]+" ");			
			}
			i++;
		}
	}
	
}