算法代码块
素数
/**
* 判断素数代码块
* @param n 带判断数
* @return 判断结果
*/
public static boolean isPrime(long n) {
if (n <= 3) {
return n > 1;
}
if (n % 2 == 0 || n % 3 == 0) {
return false;
}
long k = (long) Math.sqrt(n) + 1;
for (long i = 5; i < k; i += 6) {
if (n % i == 0 || n % (i + 2) == 0) {
return false;
}
}
return true;
}
打印层数为(2n-1)形状为(*)的沙漏
static void doPrint(int c, String s) {
for (int i = 0; i < c - 1; i++) {
int sum = 2 * (c - i) - 1;
int j = 0;
while (sum > 0) {
if (j < i) {
System.out.print(" ");
} else {
System.out.print(s);
sum--;
}
j++;
}
System.out.println();
}
for (int i = 1; i <= c; i++) {
int sum = 2 * i - 1;
int j = 0;
while (sum > 0) {
if (j < (c - i)) {
System.out.print(" ");
} else {
System.out.print(s);
sum--;
}
j++;
}
System.out.println();
}
}
用法:doPrint(3,""); --------> 打印5层符号为的沙漏
绝对值排序(从大到小)
/**
* 从大到小进行绝对值排序
* n为数组大小
*/
for (int i = 0; i < n - 1; i++) {
int max = i;
for (int j = i + 1; j < n; j++) {
if (Math.abs(array[j]) > Math.abs(array[max])) {
max = j;
}
}
if (max != i) {
int t = array[i];
array[i] = array[max];
array[max] = t;
}
}
最小公倍数
/**
* 获取两个数的最大公约数
*
* @param num1 数1
* @param num2 数2
* @return 最大公约数
*/
public static long getZuiDaGongYueShu(long num1, long num2) {
long temp = 0;
temp = num1 % num2;
if (temp == 0) return num2;
else return getZuiDaGongYueShu(num2, temp);
}
大数相加Java实现
/**
* 用字符串模拟两个大数相加
*
* @param addend 加数1
* @param augend 加数2
* @return 相加结果
*/
public static String getResult(String addend, String augend) {
StringBuffer sb = new StringBuffer();
int length1 = addend.length();
int length2 = augend.length();
int temp = 0;
if (length1 < length2) {
//2比1长
String tempStr = augend;
augend = addend;
addend = tempStr;
temp = length2;
length2 = length1;
length1 = temp;
temp = 0;
}
for (int i = length2 - 1, j = length1 - 1; i >= 0 && j >= 0; i--, j--) {
int a = addend.charAt(j) - '0';
int b = augend.charAt(i) - '0';
temp += a + b;
sb.insert(0, temp % 10);
temp /= 10;
}
if (length1 != length2) {
for (int i = length1 - length2 - 1; i >= 0; i--) {
temp += addend.charAt(i) - '0';
sb.insert(0, temp % 10);
temp /= 10;
}
}
if (temp > 0) {
sb.insert(0, temp);
}
return sb.toString();
}
快速排序
/**
* 快速排序
* @param array [description]
* @param left [description]
* @param right [description]
*/
public static void quickSort(int[] array, int left, int right) {
if (left > right) {
return;
}
//设定基准数
int temp = array[left];
//设置哨兵
int i = left;
int j = right;
while (i != j) {
//顺序很重要,要想从右往左找
while (array[j] >= temp && i < j) {
j--;
}
//再从左往右找
while (array[i] <= temp && i < j) {
i++;
}
//交换两个哨兵在数组中的位置
//两个哨兵没有相遇
if (i < j) {
int t = array[i];
array[i] = array[j];
array[j] = t;
}
}
//最终将基准数归位
array[left] = array[i];
array[i] = temp;
//继续处理左边的,这是一个递归的过程
quickSort(array, left, i - 1);
//继续处理右边的,这是一个递归的过程
quickSort(array, i + 1, right);
}