1. 程式人生 > >日記式之java演算法九九與水仙花小進階(2018.12.7)

日記式之java演算法九九與水仙花小進階(2018.12.7)

九九乘法表:

public class NNChange {
	public void finish(int number) {
		for(int i=1;i<=number;i++) {
			for(int j=1;j<=i;j++) {
				System.out.print(i+"*"+j+"="+i*j+" ");
			}
			System.out.println();
		}
	}
	public static void main(String[] args) {
		NNChange test = new NNChange();
		test.finish(9);
	}
}

水仙花:數字的各個位數的3階等於它本身:例如370(3* 3 * 3+7 * 7* 7+0* 0*0=370),主要是%取餘數與/取除數的應用。

public class Narcissus {
	/**
	 * 一位水仙花數
	 */
	public void oneNumber() {
		boolean bool = false;
		for(int i=1;i<=9;i++) {
			if(i*i*i==i) {
				System.out.println("一位數為:"+i);
				bool = true;
			}
		}
		if(bool==false) {
			System.out.println("二位數無水仙花數");
		}
	}
	/**
	 * 二位水仙花數
	 */
	public void twoNumber() {
		boolean bool = false;
		for(int i=10;i<=99;i++) {
			int a =i/10;
			int b =i%10; 
			if((a*a*a+b*b*b)==i) {
				System.out.print("二位數為:"+i+" ");
				bool = true;
			}
		}
		if(bool==false) {
			System.out.println("二位數無水仙花數");
		}
	}
	/**
	 * 三位水仙花數
	 */
	public void threeNumber() {
		boolean bool = false;
		for(int i=100;i<=999;i++) {
			int a =i/100;
			int b=i%100/10;
			int c=i%10;
			if((a*a*a+b*b*b+c*c*c)==i) {
				System.out.print("三位數為:"+i+" ");
				bool = true;
			}
		}
		System.out.println();
		if(bool==false) {
			System.out.println("三位數無水仙花數");
		}
	}
	/**
	 * 四位水仙花數
	 */
	public void fourNumber() {
		boolean bool = false;
		for(int i=1000;i<=9999;i++) {
			int a = i/1000;
			int b = i%1000/100;
			int c = i%100/10;
			int d = i%10;
			if((a*a*a+b*b*b+c*c*c+d*d*d)==i) {
				System.out.print("四位數為:"+i+" ");
				bool = true;
			}
		}
		if(bool==false) {
			System.out.println("四位數無水仙花數");
		}
	}
	public static void main(String[] args) {
		Narcissus test = new Narcissus();
		test.oneNumber();
		test.twoNumber();
		test.threeNumber();
		test.fourNumber();
	}
}