Java經典算法(二)

【程序10】

題目:將一個正整數分解質因數。例如:輸入90,打印出90=233*5。
程序分析:對n進行分解質因數,應先找到一個最小的質數k,然後按下述步驟完成:
(1)如果這個質數恰等於n,則說明分解質因數的過程已經結束,打印出即可。
(2)如果n != k,但n能被k整除,則應打印出k的值,並用n除以k的商,作爲新的正整數你n,重複執行第一步。
(3)如果n不能被k整除,則用k+1作爲k的值,重複執行第一步。

解題代碼:

import java.util.Scanner;
public class Test10 {
    public static void main(String[] args) {
        Scanner read=new Scanner(System.in);
        while(read.hasNext()){
        int n=read.nextInt();
        fenjiezhiyinshu(n);
        }
    }
    public static void fenjiezhiyinshu(int n ){
        for(int k=2;k<=n;k++){
            if(n==k) {
                System.out.println("質因數包括:"+k);
            break;}
            else if (n%k==0) {
                System.out.println("質因數包括:"+k);
                n=n/k;}
        }
    }
}

程序運行結果:
在這裏插入圖片描述

【程序11】

題目:輸入兩個正整數m和n,求其最大公約數和最小公倍數。
分析:在循環中,只要除數不等於0,用較大數除以較小的數,將小的一個數作爲下一輪循環的大數,取得的餘數作爲下一輪循環的較小的數,如此循環直到較小的數的值爲0,返回較大的數,此數即爲最大公約數,最小公倍數爲兩數之積除以最大公約數。

解題代碼:

import java.util.*;
public class Test11{
    public static void main(String[] args) {
        Scanner read =new Scanner(System.in);
        while(read.hasNext()){
        int a=read.nextInt(),b=read.nextInt();
        int  Maxyueshu= gongyinshu(a, b);
        System.out.println("您好:您輸入的數字"+a+"和"+b+"的最小公因數爲:"+Maxyueshu);
        System.out.println("您好:您輸入的數字"+a+"和"+b+"的最大公倍數爲:"+a*b/Maxyueshu);
        }
    }
    public static int gongyinshu(int a,int b) {
        if(a<b) {
            b+=a;
            a=b-a;
            b=b-a;
        }
        while(b!=0) {
            if(a==b)
                return a;
            int x=b;
            b=a%b;
            a=x;
        }
        return a;
    }
}

程序運行結果:
在這裏插入圖片描述

【程序12】

題目:一個數如果恰好等於它的因子之和,這個數就稱爲 "完數 "。例如6=1+2+3, 找出N以內的所有完數。
解題代碼:

import java.util.*;
public class Test12{
public static void main(String[] args){
    Scanner read=new Scanner(System.in);
    while(read.hasNext()){
        int N=read.nextInt();
     for(int i=1;i<=N;i++){
         int s=0;
         for(int j=1;j<=i/2;j++){//此處循環i/2次,提高效率。
            if(i % j==0){
                s=s+j;
                if(s==i)
                System.out.print(i+"    ");    
            }
         }
     }
     System.out.println("\n上行數據爲"+N+"以內所有的完數");
    }
 }
}

總結:第二個for循環,即代碼第九行,循環i/2次,提高效率。減少循環次數。
程序運行結果:
在這裏插入圖片描述

【程序13】

題目:輸入一行字符,分別統計出其中英文字母、空格、數字和其它字符的個數。
解題代碼:

import java.util.*;
public class Test13{
    public static void main(String[] args) {
        Scanner read=new Scanner(System.in);
        while(read.hasNext()){
        int zimucount=0;
        int spacecount=0;
        int numcount=0;
        int othercount=0;
        String S=read.nextLine();
        for(char c:S.toCharArray()) {
            if(Character.isLetter(c)) {
                zimucount++;
            }else if(Character.isDigit(c)) {
                numcount++;
            }else if(Character.isSpaceChar(c)){
                spacecount++;
            }else {
                othercount++;
            }
        }
        System.out.println("您好:您輸入的字符串:"+S+"中\n英文字母個數爲:"+zimucount+"\n空格數爲"
        +spacecount+"\n阿拉伯數字個數爲"+numcount+"\n其它字符個數爲:"+othercount);     
        }
    }
}

程序運行結果:

在這裏插入圖片描述

【程序14】

題目:一個整數,它加上100後是一個完全平方數,加上168又是一個完全平方數,請問該數是多少?

程序分析:先將該數加上100後再開方,再將該數加上268後再開方,如果開方後的結果滿足條件,即是結果。 因爲不知到循環次數,故for循環判斷語句恆爲真,找到即跳出循環,時間最優,因爲某數最小加100,所以循環變量i的初始值應爲-100。

解題代碼:

public class Test14 {
public static void main(String[] args) {
    for(int i=-100;true;i++) {
    if(Math.sqrt(i+100)%1==0&&Math.sqrt(i+168)%1==0) {
    System.out.println(i);
    break;}
        }
    }
}

程序運行結果:
在這裏插入圖片描述

【程序15】

題目:查找兩個字符串a,b中的最長公共子串。若有多個,輸出在較短串中最先出現的那個。
1.暴力匹配算法
解題代碼:

import java.util.*;
public class Test15{
    public static void main(String[] args){
        Scanner in = new Scanner(System.in);
        while(in.hasNext()){
            String s1 = in.nextLine();
            String s2 = in.nextLine();
            String max = s1.length() >= s2.length()?s1:s2;
            String min = s1.length() >= s2.length()?s2:s1;
            int l = 0;
            String s ="";
            for(int i=0;i<max.length();i++){
                for(int j=i+1;j<=min.length();j++){
                    if(max.contains(min.substring(i,j)) && j-i>l){
                        l=j-i;
                        s=min.substring(i,j);
                    }
                }
            }
            System.out.println("您好:你所輸入的字符串:"+s1+"與字符串"+s2+"中最先出現的最長公共子串爲:\n"+s);
        }
    }
}

程序運行結果:
在這裏插入圖片描述
用暴力方法解決的話就會有大量的回溯,每次只移動一位,若是不匹配,移動到下一位接着判斷,浪費大量時間。
1.KMP算法
未完待續……

【程序16】

解題代碼:

import java.util.*;
public class Test16 {
    public static void main (String[]args){
        int [] yuetianshu={0,0,31,59,90,120,151,181,212,243,273,304,334};
        Scanner read= new Scanner(System.in);
        System.out.println("請輸入年,月,日");  
        while(read.hasNext()){
            int year=read.nextInt(),month=read.nextInt(),day=read.nextInt(),sum=0;
            sum=yuetianshu[month]+day; /*再加上某天的天數*/ 
            if((year%400==0||(year%4==0&&year%100!=0))&& month>2)/*判斷是不是閏年*/ 
            sum++;
        System.out.println("您好:您所輸入的"+year+"年"+month+"月"+day+"日是當年的第"+sum+"天。");
        }
    }
}

題目:輸入某年某月某日,判斷這一天是這一年的第幾天?
程序運行結果:
在這裏插入圖片描述

【程序17】

題目:求1+2!+3!+…+N!的和。
解題代碼:

import java.util.*;
public class Test17{
public static void main(String[] args) {
    Scanner read=new Scanner(System.in);
    while(read.hasNext()){
        int N=read.nextInt();
        long sum=0,ver=1;
        for(int i=1;i<=N;i++) {
        ver=ver*i;
        sum+=ver;
        }
    System.out.println("1~"+N+"的階乘和爲:"+sum);
   }
    }
}

程序運行結果:
在這裏插入圖片描述

【程序17】

題目:輸入一個int型整數,按照從右向左的閱讀順序,返回一個不含重複數字的新的整數。
解題代碼:直接暴力解決。

import java.util.*;
public class Test18{
    public static void main(String[] args){
        Scanner in=new Scanner(System.in);
        while(in.hasNext()){
            String str=in.next();
            String a=str.substring(str.length()-1);
            for(int i=str.length()-2;i>=0;i--){
                    if(!a.contains(str.substring(i,i+1)))
                         a+=str.substring(i,i+1);
            }
            System.out.println(a);
        }  
    }
}

程序運行結果:
在這裏插入圖片描述

【程序18】

題目:經典實例蒙特卡羅π。

概率算法思想

基本算法思想
概率算法執行的基本過程如下:
(1)將問題轉化爲相應的幾何圖形S, S 的面積是容易計算的,問題的結果往往對應幾何圖形中某一部分S1 的面積。
(2)然後,向幾何圖形中隨機撒點。
(3)統計幾何圖形S 和 S1 中的點數。根 據 S 的面積和S1 面積的關係以及各圖形中的點數來計算得到結果。
(4) 判斷上述結果是否在需要的精度之內,如果未達到精度則執行步驟(2)。如果達到精度,則輸出近似結果。

概率算法大致分爲如下4 種形式:
• 數值概率算法。
• 蒙特卡羅 (MonteCarlo)算法。
• 拉斯維加斯 (Las Vegas)算法。
• 舍伍德 (Sherwood)算法。

題目:經典實例蒙特卡羅π
蒙特卡羅算法解析圖
如果均勻的在正方形中撒點,落入陰影部分的概率爲π/4
根據概率統計的規律,只要點足夠多就可以得到非常近似的結果

解題代碼

import java.util.*;
public class Test18Pi{
public static void main(String[] args) {
    Scanner read=new Scanner(System.in);
    while(read.hasNext()){
        long n=read.nextLong();
        System.out.println("根據您的輸入計算獲得PI的近似值爲:"+getPI(n));}}
public static double getPI(long n){
	double x,y;
	int sum = 0;
	for(int i = 0;i<n*n;i++){
		x = Math.random();
		y = Math.random();
		if(x*x+y*y<=1){
			sum++;
		}
	}
	return sum*4.0/n/n;
    }
}

程序運行結果:
在這裏插入圖片描述

路阻且長之Java學習:

API中的重要類(一):
https://blog.csdn.net/Veer_c/article/details/103803248
API中的重要類(二):
https://blog.csdn.net/Veer_c/article/details/103807515
API中的重要類(三):
https://blog.csdn.net/Veer_c/article/details/103808054

Java中的IO流(一):
https://blog.csdn.net/Veer_c/article/details/103833045
Java中的IO流(二):
https://blog.csdn.net/Veer_c/article/details/103833423
Java中的IO流(三):
https://blog.csdn.net/Veer_c/article/details/103833811

Java多線程(一):
https://blog.csdn.net/Veer_c/article/details/103842078
Java多線程(二):
https://blog.csdn.net/Veer_c/article/details/103842263
Java多線程(三):
https://blog.csdn.net/Veer_c/article/details/103842317
Java多線程(四):
https://blog.csdn.net/Veer_c/article/details/103842602

網絡編程上(UDP):
https://blog.csdn.net/Veer_c/article/details/103843591
網絡編程下(TCP):
https://blog.csdn.net/Veer_c/article/details/103843825

MySQL數據庫(一):
https://blog.csdn.net/Veer_c/article/details/103844059
MySQL數據庫(二):
https://blog.csdn.net/Veer_c/article/details/103844537
MySQL數據庫(三):
https://blog.csdn.net/Veer_c/article/details/103844739

JDBC技術(一):
https://blog.csdn.net/Veer_c/article/details/103845176
JDBC技術(二):
https://blog.csdn.net/Veer_c/article/details/103879890
JDBC技術(三):
https://blog.csdn.net/Veer_c/article/details/103880021
JDBC技術(四):
https://blog.csdn.net/Veer_c/article/details/103882264

HTML的基礎框架(一):
https://blog.csdn.net/Veer_c/article/details/103882385
HTML的基礎框架(二):
https://blog.csdn.net/Veer_c/article/details/103882684

CSS入門(一)
https://blog.csdn.net/Veer_c/article/details/103882856

CSS入門(二):
https://blog.csdn.net/Veer_c/article/details/103883102

JavaScript實用案例與常見問題(一):
https://blog.csdn.net/Veer_c/article/details/103894959
JavaScript實用案例及常見問題(二):
https://blog.csdn.net/Veer_c/article/details/103895166

BOM編程詳解:
https://blog.csdn.net/Veer_c/article/details/103895433

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章