算法小结
格式
java加快输入和输出
传统的Scanner输入比较慢,用下面的InputReader类加快输入和输出 之前的输入和输出分别用实例化的reader和writer 去替换System.in和System.out reader.nextInt() writer.print()
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
solution();
}
public static void solution() {
InputReader reader = new InputReader(System.in);
PrintWriter writer = new PrintWriter(System.out, true);
int T = reader.nextInt();
int[] arr = new int[T];
for (int i = 0; i < arr.length; i++) {
String str = reader.next();
arr[i] = process(str);
}
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
public static void test() {
}
public static int process(String str) {
int res = 0;
return res;
}
}
class InputReader {
private BufferedReader reader = null;
private StringTokenizer tokenizer = null;
public InputReader(InputStream inputStream) {
this.reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() {
while (tokenizer == null || !tokenizer.hasMoreElements()) {
try {
tokenizer = new StringTokenizer(reader.readLine());
} catch (IOException e) {
}
}
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
}
测试
以排序为例
package 排序;
import java.util.Arrays;
public class Solve {
public static void swap(int[] arr ,int i,int j){
if(arr.length == 0 || arr == null){
return;
}
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
public static void qsort(int[] arr,int left,int right){
if (left<right) {
int random = left + (int)(Math.random()*(right - left));
swap(arr,random,right);
int[] p = partition(arr,left,right);
partition(arr,left,p[0] - 1);
partition(arr,p[1] + 1,right);
}
}
public static int[] partition(int[] arr,int left,int right){
int less = left - 1;
int more = right;
while(left < more){
if(arr[left] < arr[right]){
swap(arr,++less,left++);
}else if(arr[left] > arr[right]){
swap(arr,--more,left);
}else{
left++;
}
}
swap(arr,more,right);
return new int[] {less+1,more};
}
public static int[] MySort (int[] arr) {
if(arr == null || arr.length < 2){
return arr;
}
qsort(arr,0,arr.length - 1);
return arr;
}
public static void comparator(int []arr) {
Arrays.sort(arr);
}
public static int [] generateRandomArray(int maxSize ,int maxValue) {
int []arr = new int [(int)((maxSize + 1)*Math.random())];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int)((maxValue + 1)*Math.random()) - (int)(maxValue*Math.random());
}
return arr;
}
public static int [] copy(int []arr) {
if (arr == null) {
return null;
}
int res[] = new int [arr.length];
for (int i = 0; i < res.length; i++) {
res[i] = arr[i];
}
return res;
}
public static boolean isEqual(int []arr1,int []arr2 ) {
if (arr1 ==null && arr2 == null) {
return true;
}if ((arr1 == null && arr1 != null ) || (arr1 != null && arr1 == null )) {
return false;
}
if (arr1.length != arr2.length) {
return false;
}
for (int i = 0; i < arr2.length; i++) {
if (arr1[i] != arr2[i]) {
return false;
}
}
return true;
}
public static void printArray(int arr[]) {
if (arr == null) {
return ;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
int testTime = 5;
int maxSize = 4;
int maxValue = 9;
boolean flag = true;
for (int i = 0; i < testTime; i++) {
int []arr1 = generateRandomArray(maxSize,maxValue);
int []arr2 = copy(arr1);
MySort(arr1);
comparator(arr2);
if (!isEqual(arr1, arr2)) {
printArray(arr1);
printArray(arr2);
flag = false;
break;
}
}
System.out.println(flag ? "ok" : "bug");
}
}
产生随机数
public static int[] generateRandomArray(int maxSize, int maxValue) {
int[] arr = new int[(int) ((maxSize) * Math.random()) + 1];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) ((maxValue + 1) * Math.random())
- (int) ((maxValue + 1) * Math.random());
}
return arr;
}
public static int Random_int(int a, int b) {
return (int) (Math.random() * 10 % (a - b) + a);
}
public static double Random_double(double a, double b) {
return Math.random() * (b - a) + a;
}
数学
最大公约数和最小公倍数
注意:
求两个数的最大公约数和最小公倍数的前提是两个数是正整数,非正整数无意义。
扩展:
利用最大公约数可以化解分数。
公式:分子/分母 = 分子/gcd(分子,分母) / (分母 / gcd())
如: 24 / 18 = 24 / gcd(24,18) / (18/gcd(18,24))
import java.util.Scanner;
public class Gcd_LCM {
public static int gcd(int a,int b) {
while (a != 0) {
int temp= b % a;
b = a;
a = temp;
}
return b;
}
public static int gcd2(int a, int b) {
return b == 0 ? a : gcd2(b, a % b);
}
public static int LCM(int a,int b) {
return a/gcd(a,b) * b;
}
public static String huajian(int a, int b) {
if (a % b == 0 ) {
return "" + (a / b);
} else {
return ""+(a / gcd(a, b) + "/" + b / gcd(a, b));
}
}
public static void main(String[] args) {
int a = 16,b = 12;
System.out.println(a+","+b+"最大公约数是:"+gcd(a,b));
System.out.println(a+","+b+"最小公倍数是:"+LCM(a,b));
System.out.println(huajian(-42, 15));
}
}
素数
[1] 判断一个数是否是素数
[2] 输出[low,hight]之间的素数
package math;
public class Prime {
public static boolean isPrime(int n) {
int i ;
boolean flag = false;
for (i=2;i <= (int)Math.sqrt(n);i++) {
if(n % i ==0) {
flag = true;
break;
}
}
return !flag;
}
public static void prime_ab(int low,int hight) {
int index = 0;
for (int i = low; i <= hight; i++) {
if(isPrime(i)) {
System.out.println(i);
index++;
}
}
System.out.println("素数的个数:"+index+1);
}
public static void test() {
int count = 0;
int j = 103;
int k = 1;
while (j <= 10000) {
if (isPrime(j) && j % 10 == 3) {
count++;
System.out.printf("%5d ",j);
if(k % 5 == 0) {
System.out.println();
}
k++;
}
j++;
}
System.out.println("\ncount = " + count);
System.out.println("---------");
count = 0;
k = 1;
for (int i = 100; i <= 10000; i++) {
if(isPrime(i)) {
count++;
System.out.printf("%5d ",i);
if (k % 5==0) {
System.out.println();
}
k++;
}
}
System.out.println("\ncount="+count);
System.out.println("---------");
}
public static void main(String[] args) {
prime_ab(100,10000);
}
}
阶乘和组合
package math;
public class 阶乘_组合 {
public static long An(int n) {
if (n == 0 || n == 1) {
return 1;
}
int An = 1;
for (int i = 2; i <= n; i++) {
An *= i;
}
return An;
}
public static int C(int m,int n) {
if (m == 0 || n == 0) {
return 1;
}
if (m > n / 2) {
m = n - m;
}
int fengzi = 1;
int fengmu = 1;
while(m != 0) {
fengzi *= n;
fengmu *= m;
n--;
m--;
}
return fengzi/fengmu;
}
public static void main(String[] args) {
int n = 16;
System.out.println(An(n));
System.out.println(C(5,20));
System.out.println("9! = "+An(9));
}
}
欧几里得算法
package math;
public class 扩展欧几里得算法 {
static int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
public static long[] ex_gcd(long a, long b, long[] x, long[] y) {
long gcd;
long[] result = new long[3];
if (b == 0) {
result[0] = a;
result[1] = x[0];
result[2] = y[0];
return result;
}
long q = a / b;
long tx1 = x[0] - q * x[1];
long ty1 = y[0] - q * y[1];
long[] tx = { x[1], tx1 };
long[] ty = { y[1], ty1 };
return ex_gcd(b, a % b, tx, ty);
}
public static long[] ex_gcd(long a, long b) {
long[] x = { 1, 0 };
long[] y = { 0, 1 };
return ex_gcd(a, b, x, y);
}
}
矩阵
矩阵的打印
public static void printMatrix(long[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
矩阵的乘法
package matrix;
import java.util.Scanner;
public class MatrixMultiply {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
long[][] a = new long[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
a[i][j] = sc.nextLong();
}
}
int p = sc.nextInt();
long[][] b = new long[n][p];
for (int i = 0; i < n; i++) {
for (int j = 0; j < p; j++) {
b[i][j] = sc.nextLong();
}
}
System.out.println();
printMatrix(matrixMultiply(a, b));
}
public static void printMatrix(long[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public static long[][] matrixMultiply(long[][] a,long[][] b) {
int n = a.length;
int m = a[0].length;
int p = b[0].length;
if(a[0].length != b.length) throw new IllegalArgumentException();
long[][] res = new long[m][p];
for(int i = 0;i < m;i++) {
for (int j = 0; j < p; j++) {
for (int k = 0; k < n; k++) {
res[i][j] += a[i][k] * b[k][j];
}
}
}
return res;
}
}
输入
2 2
1 2
1 -1
3
1 2 -3
-1 1 2
输出
-1 4 1
2 1 -5
矩阵的转置
package matrix;
import java.util.Scanner;
public class MatrixTranspose {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int m = sc.nextInt();
int n = sc.nextInt();
int[][] a = new int[m][n];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[0].length; j++) {
a[i][j] = sc.nextInt();
}
}
printMatrix(matrixTranspose(a));
}
public static void printMatrix(int[][] a) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.println();
}
}
public static int[][] matrixTranspose(int[][] a) {
int[][] res = new int[a[0].length][a.length];
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
res[j][i] = a[i][j];
}
}
return res;
}
}
字符串
字符串常见的操作
package string;
public class _01StringBasicOpeMethod {
public static void main(String args[]){
String str = "如何才能变得像棋哥一样优秀?算了吧,憋吹牛逼!";
System.out.println(str);
int length = str.length();
System.out.println("字符串的长度为:"+length);
String str1 = "0123456789";
char ch = str.charAt(7);
System.out.println("字符串中的第8个字符为:"+ch);
char ch2 = str1.charAt(9);
System.out.println("字符串中的第9个字符为:"+ch2);
char chardst[] = new char[20];
System.out.print("chardst:");
System.out.println(chardst);
for (int i = 0; i < chardst.length; i++) {
chardst[i] = 'i';
}
System.out.println(chardst);
str.getChars(0,14,chardst,5);
System.out.println("字符数组中存放的内容为:"+chardst);
System.out.println(chardst);
}
}
字符串的比较方法
package string;
public class _02StringCompareMethod {
public static void main(String[] args) {
String str1 = "abcd";
String str2 = "Abcd";
String str3 = "abdc";
String str4 = "abcdef";
if (str1.compareTo(str2) > 0) {
System.out.println(str1 + " > " + str2);
}
if (str1.compareTo(str3) < 0) {
System.out.println(str1 + " < " + str3);
}
String str5 = "ab cd";
String str6 = "abcd";
if (str5.compareTo(str6) < 0) {
System.out.println(str5 + " < " + str6);
}
String str7 = "1234";
String str8 = "1234";
String str9 = "1234 ";
if (str7.equals(str8)) {
System.out.println(str7+"="+str8);
}
if (!str7.equals(str9)) {
System.out.println(str7+"!="+str9+", ");
}
String str10 = "abcd";
String str11 = "Abcd";
if (str10.equalsIgnoreCase(str11)) {
System.out.println(str10+"="+str11);
}
}
}
字符串与其他数据类型的转换
package string;
public class _03字符串与其他数据类型的转换 {
public static void main(String args[]){
boolean bool = Boolean.getBoolean("false");
int integer = Integer.parseInt("20");
long LongInt = Long.parseLong("1024");
float f = Float.parseFloat("1.521");
double d = Double.parseDouble("1.52123");
char ch = "棋哥".charAt(0);
System.out.println(ch);
String strb1 = String.valueOf(bool);
String stri1 = String.valueOf(integer);
String strl1 = String.valueOf(LongInt);
String strf1 = String.valueOf(f);
String strd1 = String.valueOf(d);
String strch1 = String.valueOf(ch);
}
}
_04字符串查找
package string;
public class _04字符串查找 {
public static void main(String args[]){
String str = "How qi bocome handsome like qi ge";
System.out.println("该字符串为:"+str);
int index1 = str.indexOf(" ");
int index2 = str.indexOf(" ",4);
System.out.println("第一个空格所在索引为:"+index1);
System.out.println("索引4以后的第一个空格所在索引为:"+index2);
System.out.println("*****************");
int index3 = str.lastIndexOf(" ");
int index4 = str.lastIndexOf(" ",10);
System.out.println("最后一个空格所在索引为:"+index3);
System.out.println("索引10以前最后一个空格所在索引为:"+index4);
System.out.println("*****************");
int index5 = str.indexOf("qi");
int index6 = str.indexOf("qi",5);
System.out.println("子字符串qi第一次出现位置的索引号为:"+index5);
System.out.println("索引5以后子字符串qi第一次出现位置的索引号为:"+index6);
System.out.println("*****************");
int index7 = str.lastIndexOf("qi");
int index8 = str.lastIndexOf("qi",5);
System.out.println("子字符串qi最后一次出现位置的索引号为:"+index7);
System.out.println("索引号5以后子字符串qi最后一次出现位置的索引号为:"+index8);
}
}
_05字符串截取与拆分
package string;
public class _05字符串截取与拆分 {
public static void main(String args[]){
String str = "How to cut and split strings";
System.out.println("字符串为:"+str);
int length = str.length();
System.out.println("字符串长度为:"+length);
int firstIndex = str.indexOf(' ');
int lastIndex = str.lastIndexOf(' ');
System.out.println("第一个空格的索引号为:"+firstIndex);
System.out.println("最后一个空格的索引号为:"+lastIndex);
String firstWord = str.substring(0,firstIndex);
String lastWord = str.substring(lastIndex+1,length);
System.out.println("第一个单词为:"+firstWord);
System.out.println("最后一个单词为:"+lastWord);
String stringArray[] = str.split(" ");
System.out.println("拆分之后的各个词汇为:");
for(int i = 0;i<stringArray.length;i++){
System.out.print(stringArray[i]+"\t");
}
}
}
_06字符串的替换或修改
package string;
public class _06替换或修改 {
public static void main(String args[]){
String str1 = "vbasic";
String str2 = "Vbasic";
System.out.println("str1 = "+str1);
System.out.println("str2 = "+str2);
String str3 = str1.concat(str2);
System.out.println("str1和str2合并后的字符串为:"+str3);
String str4 = str1.toLowerCase();
System.out.println("str1的字符全部转换为小写:"+str4);
String str5 = str2.toUpperCase();
System.out.println("str2的字符全部转换为大写:"+str5);
String str6 = str1.replaceFirst("(?i)VBASIC","C++");
String str7 = str2.replaceFirst("(?-i)VBASIC","C++");
System.out.println("替换后的str1:"+str6);
System.out.println("替换后的str2:"+str7);
}
}
字符串的加密和解密
package string;
public class 加密解密 {
public static String jiaMi(String str1,String str2,String string) {
char[] c = string.toCharArray();
String ans = "";
for (int i = 0; i < c.length; i++) {
int j = str1.indexOf(c[i]);
ans += str2.substring(j, j + 1);
}
return ans;
}
public static String jieMi(String str1,String str2 ,String string) {
char[] ch = string.toCharArray();
String ans = "";
for (int i = 0; i < ch.length; i++) {
int j = str2.indexOf(ch[i]);
ans += str1.substring(j, j + 1);
}
return ans;
}
public static void main(String[] args) {
String str1 = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String str2 = "yxmdacikntjhqlgoufszpwbrevYXMDACIKNTJHQLGOUFSZPWBREV";
String str = "YeRikGSunlRzgDlvRwYkXkrGWWhXaA";
System.out.println(jiaMi(str1, str2, str));
String string = "EaFnjISplhFviDhwFbEjRjfIBBkRyY";
System.out.println(jieMi(str1, str2, string));
}
}
字符串大小写的转换
package string;
public class 字符串大小写转换 {
public class ToLowerUpperCase {
private String str;
public String toLowerCase(String str,int i) {
return str.toLowerCase();
}
}
public static void main(String[] args) {
String str = "Test 例子 Demo 哈哈 ";
System.out.println("[" + str + "] 转小写 [" + str.toLowerCase() + "]");
String str2 = "Test 例子 Demo 哈哈 ";
System.out.println("[" + str2 + "] 转大写 [" + str2.toUpperCase() + "]");
String str3 = "DEPTNO";
System.out.println("[" + str + "] 转小写 [" + str3.toLowerCase() + "]");
String str4 = "Test 例子 Demo 哈哈 ";
System.out.println("[" + str2 + "] 转大写 [" + str4.toUpperCase() + "]");
}
}
回文串
package string;
import java.util.ArrayList;
import java.util.Scanner;
public class 回文串 {
public static boolean isPalindromeString(String string) {
char[] ch = string.toCharArray();
for (int i = 0; i < ch.length / 2; i++) {
if (ch[i] != ch[ch.length - 1 - i]) {
return false;
}
}
return true;
}
public static boolean isPalindromeString2(String string) {
String string2 = string.toLowerCase();
char[] ch = string2.toCharArray();
for (int i = 0; i < ch.length / 2; i++) {
if (ch[i] != ch[ch.length - 1 - i]) {
return false;
}
}
return true;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> string = new ArrayList<String>();
string.add("Abcba");
for (int i = 0; i < string.size(); i++) {
System.out.println(string.get(i));
System.out.println("区分大小写:");
if (isPalindromeString(string.get(i))) {
System.out.println("Yes");
} else {
System.out.println("No");
}
System.out.println("不区分大小写:");
if (isPalindromeString2(string.get(i))) {
System.out.println("Yes");
} else {
System.out.println("No");
}
}
}
}
大数运算
大整数BigInteger
package 大数运算;
import java.math.BigInteger;
public class BigIntegerTest {
public static void main(String[] args) {
BigInteger b = new BigInteger("123");
int a1 = 456;
BigInteger a = BigInteger.valueOf(a1);
long c1 = 123;
BigInteger c = BigInteger.valueOf(c1);
System.out.println("==大整数的四则运算==");
a. add(b);
System.out.printf(a +"+"+ b +" = "+a.add(b)+"\n");
a.subtract(b);
System.out.printf(a +"-"+ b +" = "+a.subtract(b)+"\n");
a.multiply(b);
System.out.printf(a +"*"+ b +" = "+a.multiply(b)+"\n");
a.divide(b);
System.out.printf(a +"/"+ b +" = "+a.divide(b)+"\n");
System.out.println("===常用方法===");
a.mod(b);
System.out.printf(a +".mod("+ b +") = "+a.mod(b)+"\n");
a.gcd(b);
System.out.printf(a +".gcd("+ b +") = "+a.gcd(b)+"\n");
a.max(b);
System.out.printf(a +".max("+ b +") = "+a.max(b)+"\n");
a.min(b);
System.out.printf(a +".min("+ b +") = "+a.min(b)+"\n");
System.out.println("===大整数比较大小===");
a.equals(b);
System.out.println(a.equals(b));
a.compareTo(b);
BigInteger compareTo1 = new BigInteger("-123");
BigInteger compareTo2 = new BigInteger("123");
BigInteger compareTo3 = new BigInteger("123");
BigInteger compareTo4 = new BigInteger("200");
System.out.println(compareTo1.compareTo(compareTo2));
System.out.println(compareTo2.compareTo(compareTo3));
System.out.println(compareTo4.compareTo(compareTo3));
System.out.println("===BigInteger中的常数====");
BigInteger big0 = BigInteger.ZERO;
System.out.println(big0);
BigInteger big1 = BigInteger.ONE;
System.out.println(big1);
BigInteger big10 = BigInteger.TEN;
System.out.println(big10);
System.out.println("===求大整数的位数====");
BigInteger biglength = new BigInteger("123456789");
a.toString().length();
System.out.println(biglength.toString().length());
}
}
大浮点数
package 大数运算;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.RoundingMode;
public class BigDecimalTest {
public static void main(String[] args) {
System.out.println(0.2 + 0.1);
System.out.println(0.3 - 0.1);
System.out.println(0.2 * 0.1);
System.out.println(0.3 / 0.1);
System.out.println("创建BigDecimal");
BigDecimal bigBigDecimal = new BigDecimal("12.3456");
System.out.println(bigBigDecimal);
BigDecimal bDouble = new BigDecimal(2.3);
System.out.println("bDouble=" + bDouble);
double d = 0.123;
BigDecimal bigdouble = new BigDecimal(Double.toString(d));
float f = 0.12f;
BigDecimal bigfloat = new BigDecimal(Float.toString(f));
BigDecimal bString = new BigDecimal("2.3");
System.out.println("bString=" + bString);
int int1 = 34;
BigDecimal bigint = new BigDecimal(int1);
System.out.println(int1);
long long1 = 123456789;
BigDecimal biglong = new BigDecimal(long1);
System.out.println(long1);
BigDecimal first = new BigDecimal("369");
BigDecimal second = new BigDecimal("123");
System.out.println("a + b = " + first.add(second));
System.out.println("a - b = " + first.subtract(second));
System.out.println("a * b = " + first.multiply(second));
System.out.println("a / b = " + first.divide(second));
BigDecimal biga = new BigDecimal("456");
BigDecimal bigb = new BigDecimal("123");
BigDecimal c = new BigDecimal("2.135");
c = c.setScale(2, RoundingMode.HALF_UP);
System.out.println(c);
c = c.setScale(0, RoundingMode.HALF_UP);
System.out.println(c);
System.out.println(biga.divide(bigb,1,BigDecimal.ROUND_HALF_UP));
System.out.printf(first +".max("+ second +") = "+first.max(second)+"\n");
System.out.printf(first +".min("+ second +") = "+first.min(second)+"\n");
BigInteger a = BigInteger.ONE;
BigInteger b = BigInteger.ONE;
for (int i = 3; i < 300; i++) {
BigInteger tmp = b;
b = a.add(b);
a = tmp;
}
BigDecimal res = new BigDecimal(a,110).divide(new BigDecimal(b,110), BigDecimal.ROUND_HALF_DOWN);
System.out.println(res.toPlainString().substring(0,103));
}
}
快速幂运算
package 快速幂;
import java.math.BigInteger;
import java.time.Duration;
import java.time.Instant;
public class 快速幂 {
public static long fastpower(long base,long power) {
long result = 1L;
while (power > 0) {
if ((power & 1) == 1) {
result *= base;
}
power = power >> 1;
base *= base;
}
return result;
}
public static long fastpower2(long base,long power) {
long result = 1;
while (power > 0) {
if (power % 2 == 1) {
result *= base;
}
power = power / 2;
base *= base;
}
return result;
}
public static long fastpower1(long base,long power) {
long result = 1;
while (power > 0) {
if (power % 2 == 1) {
result *= base;
power--;
}else {
base = base*base;
power = power / 2;
}
}
return result;
}
public static void main(String[] args) {
System.out.println(fastpower1(2, 10));
System.out.println(fastpower2(2, 10));
System.out.println(fastpower(2, 10));
System.out.println((long)Math.pow(2, 10));
int testTime = 1000;
boolean flag = true;
for (int i = 2; i < testTime; i++) {
for (int j = 2; j < testTime; j++) {
if (fastpower(i, j) != fastpower1(i, j)
|| fastpower(i, j) != fastpower2(i, j)) {
System.out.println(fastpower(2, 10));
System.out.println(fastpower1(2, 10));
System.out.println(fastpower2(2, 10));
flag = false;
}
}
}
System.out.println(flag ? "ok" : "bug");
System.out.println(fastpower2(2, 62));
}
}
模运算
package 模运算;
public class 模运算的性质 {
public static int method1(long a,long b,int p) {
return (int)((a % p + b % p) % p);
}
public static int method2(long a,long b,int p) {
return (int)((a % p - b % p) % p);
}
public static int method3(long a,long b,int p) {
return (int)((a % p * b % p) % p);
}
public static int method4(long a,long b,int p) {
return (int)(((a % p)^b) % p);
}
public static int method5(long a,long b,int p) {
return (int)(((a % p) * ( b % p)) % p);
}
public static void main(String[] args) {
System.out.println(method1(23, 45, 19));
System.out.println(method2(23, 45, 19));
System.out.println(method3(23, 45, 19));
System.out.println(method4(23, 45, 19));
System.out.println(method5(3, 4, 5));
System.out.println(34 % 5);
}
}
几何
三角形
package 几何;
public class 三角形 {
public static double S(double a,double b,double c) {
double s;
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
public static double S3(double a,double b,double c,double d,double e,double f) {
return Math.abs((a*d+ b*e+c*f- a*f- b*c-d*e)/2);
}
public static void main(String[] args) {
double a = 5;
double b = 7;
double c = Math.sqrt(a*a + b*b);
System.out.println(S(a,b,c));
System.out.println(S3(0,0,0,a,b,0));
}
}
圆
package 几何;
public class 圆 {
public static double circumference(double r) {
return 2*Math.PI*r;
}
public static double area(double r) {
return Math.PI*r*r;
}
public static double surface_area(double r,double h) {
return 2*Math.PI*r*(r + h);
}
}
日历
闰年
package 日历;
public class IsLeap {
public static boolean isLeap(int year) {
return year % 4== 0 && year % 100 != 0 || year % 400 == 0;
}
public static void main(String[] args) {
for (int i = 2000; i <= 2050; i++) {
if (isLeap(i)) {
System.out.printf("%d\n",i);
}
}
}
}
递归和动态规划
换钱的方法数
package 递归_动态规划;
public class 换钱的方法数 {
public static void main(String[] args) {
int[] arr = { 10, 5, 1, 25 };
int aim = 2200;
long start = 0;
long end = 0;
start = System.currentTimeMillis();
System.out.println(coins1(arr, aim));
end = System.currentTimeMillis();
System.out.print("coins1:");
System.out.println((end - start) + "ms");
start = System.currentTimeMillis();
System.out.println(coins2(arr, aim));
end = System.currentTimeMillis();
System.out.print("coins2:");
System.out.println((end - start) + "ms");
start = System.currentTimeMillis();
System.out.println(coins3(arr, aim));
end = System.currentTimeMillis();
System.out.print("coins3:");
System.out.println((end - start) + "ms");
start = System.currentTimeMillis();
System.out.println(coins4(arr, aim));
end = System.currentTimeMillis();
System.out.print("coins4:");
System.out.println((end - start) + "ms");
start = System.currentTimeMillis();
System.out.println(coins5(arr, aim));
end = System.currentTimeMillis();
System.out.print("coins5:");
System.out.println((end - start) + "ms");
}
public static int coins1(int[] arr,int aim) {
if (arr == null || aim < 0 || arr.length == 0) {
return 0;
}
return process1(arr, 0, aim);
}
public static int process1(int[] arr,int index, int aim) {
int res = 0;
if (index == arr.length) {
return res = aim == 0 ? 1 : 0;
}else {
for (int i = 0; arr[index] * i <= aim; i++) {
res += process1(arr, index + 1, aim - arr[index] * i);
}
}
return res;
}
public static int coins2(int[] arr,int aim) {
if (arr == null || aim < 0 || arr.length == 0) {
return 0;
}
int[][] map = new int[arr.length + 1][aim + 1];
return process2(arr, 0, aim,map);
}
public static int process2(int[] arr,int index, int aim, int[][] map) {
int res = 0;
if (index == arr.length) {
return res = aim == 0 ? 1 : 0;
}else {
int mapValue = 0;
for (int i = 0; arr[index] * i <= aim; i++) {
mapValue = map[index + 1][aim - arr[index] * i];
if (mapValue != 0) {
res += mapValue == -1 ? 0 : mapValue;
}else {
res += process2(arr, index + 1, aim - arr[index] * i, map);
}
}
}
map[index][aim] = res == 0 ? -1 : res;
return res;
}
public static int coins3(int[] arr,int aim) {
if (arr == null || aim < 0 || arr.length == 0) {
return 0;
}
int[][] dp = new int[arr.length][aim + 1];
for (int i = 0; i < arr.length; i++) {
dp[i][0] = 1;
}
for (int j = 1; j * arr[0] <= aim; j++) {
dp[0][arr[0] * j] = 1;
}
int sum = 0;
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j <= aim; j++) {
sum = 0;
for (int k = 0; j - k * arr[i] >= 0; k++) {
sum += dp[i - 1][j - k * arr[i]];
}
dp[i][j] = sum;
}
}
return dp[arr.length - 1][aim];
}
public static int coins4(int[] arr,int aim) {
if (arr == null || aim < 0 || arr.length == 0) {
return 0;
}
int[][] dp = new int[arr.length][aim + 1];
for (int i = 0; i < arr.length; i++) {
dp[i][0] = 1;
}
for (int j = 1; j * arr[0] <= aim; j++) {
dp[0][arr[0] * j] = 1;
}
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j <= aim; j++) {
dp[i][j] = dp[i - 1][j];
dp[i][j] += j - arr[i] >= 0 ? dp[i][j - arr[i]] : 0;
}
}
return dp[arr.length - 1][aim];
}
public static int coins5(int[] arr,int aim) {
if (arr == null || aim < 0 || arr.length == 0) {
return 0;
}
int[] dp = new int[aim + 1];
for (int i = 0; i < arr.length; i++) {
dp[0] = 1;
}
for (int j = 1; j * arr[0] <= aim; j++) {
dp[arr[0] * j] = 1;
}
for (int i = 1; i < arr.length; i++) {
for (int j = 1; j <= aim; j++) {
dp[j] += j - arr[i] >= 0 ? dp[j - arr[i]] : 0;
}
}
return dp[aim];
}
}
一维动态规划
package 递归_动态规划;
public class 机器人到达指定位置方法数 {
public static void main(String[] args) {
int N = 7;
int M = 4;
int K = 9;
int P = 5;
System.out.println(way1(N, M, K, P));
System.out.println(way2(N, M, K, P));
System.out.println(way3(N, M, K, P));
}
public static int walk(int N ,int cur, int rest, int P){
if (rest == 0) {
return cur == P ? 1 : 0;
}
if (cur == 1) {
return walk(N, 2, rest - 1, P);
}
if (cur == N) {
return walk(N, N - 1, rest - 1, P);
}
return walk(N, cur - 1, rest - 1, P) + walk(N, cur + 1, rest - 1, P);
}
public static int way1(int N ,int M, int K, int P) {
if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
return 0;
}
return walk(N, M, K, P);
}
public static int way2(int N ,int M, int K, int P) {
if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
return 0;
}
int[][] dp = new int[K + 1][N + 1];
dp[0][P] = 1;
for (int i = 1; i < dp.length; i++) {
for (int j = 1; j < dp[0].length; j++) {
if (j == 1) {
dp[i][j] = dp[i - 1][2];
}else if (j == N ) {
dp[i][j] = dp[i - 1][N - 1];
}else {
dp[i][j] = dp[i - 1][j - 1] + dp[i - 1][j + 1];
}
}
}
printArray(dp);
return dp[K][M];
}
public static int way3(int N ,int M, int K, int P) {
if (N < 2 || K < 1 || M < 1 || M > N || P < 1 || P > N) {
return 0;
}
int[] arr = new int[N + 1];
arr[P] = 1;
for (int i = 1; i <= K; i++) {
int LeftUp = arr[1];
for (int j = 1; j < arr.length; j++) {
int temp = arr[j];
if (j == 1) {
arr[j] = arr[2];
}else if (j == arr.length - 1) {
arr[j] = LeftUp;
}else {
arr[j] = LeftUp + arr[j + 1];
}
LeftUp = temp;
}
for (int j = 0; j < arr.length; j++) {
System.out.print(arr[j] + " ");
}
System.out.println();
}
return arr[M];
}
static void printArray(int[][] arr) {
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[0].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
n皇后问题
package 递归_动态规划;
public class NQueens {
public static int nQueens(int n) {
if (n < 1) {
return 0;
}
int[] record = new int[n];
return process(record, 0, n);
}
public static int process(int[] record,int i,int n) {
if (i == n) {
return 1;
}
int res = 0;
for (int j = 0; j < n; j++) {
if (isValid(record,i,j)) {
record[i] = j;
res += process(record, i + 1, n);
}
}
return res;
}
public static boolean isValid(int[] record,int i,int j) {
for (int k = 0; k < i; k++) {
if (record[k] == j || (Math.abs(record[k] - j) == Math.abs(k - i) )) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int n = 14;
System.out.println(nQueens(n));
System.out.println(nQueens(n));
}
}
|