目录
[五、实际应用示例:RSA 加密算法核心计算](#五、实际应用示例:RSA 加密算法核心计算)
一、基本数据类型
这是进行数字计算最高效的方式,直接在栈上分配内存。它们分为整数型和浮点型。
类型 | 大小 | 取值范围 | 默认值 | 使用场景 |
---|---|---|---|---|
byte |
8位 (1字节) | -128 ~ 127 | 0 | 节省空间,如处理二进制数据、文件流 |
short |
16位 (2字节) | -32,768 ~ 32,767 | 0 | 较少使用,可用于兼容C语言short等特定场景 |
int |
32位 (4字节) | -2³¹ ~ 2³¹-1 (约 -21亿 ~ 21亿) | 0 | 最常用,一般整数计算的首选 |
long |
64位 (8字节) | -2⁶³ ~ 2⁶³-1 | 0L | 需要表示非常大整数时,如时间戳、全球唯一ID |
类型 | 大小 | 取值范围 | 默认值 | 精度 | 使用场景 |
---|---|---|---|---|---|
float |
32位 (4字节) | ≈ ±3.4e+38F | 0.0f | 约 6-7 位有效小数 | 图形处理、科学计算(对内存敏感时) |
double |
64位 (8字节) | ≈ ±1.7e+308 | 0.0 | 约 15-16 位有效小数 | 最常用,默认的浮点类型 |
java
import java.util.Scanner;
public class PrimitiveMathOperations {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Java基本数据类型数学计算示例");
System.out.println("==============================");
// 整数类型计算示例
integerOperations();
// 浮点数类型计算示例
floatingPointOperations();
// 类型转换示例
typeConversionExamples();
// 使用Math类进行高级计算
mathClassExamples();
scanner.close();
}
// 整数类型操作示例
public static void integerOperations() {
System.out.println("\n1. 整数类型操作示例:");
int a = 15;
int b = 4;
System.out.println("a = " + a + ", b = " + b);
System.out.println("加法: a + b = " + (a + b));
System.out.println("减法: a - b = " + (a - b));
System.out.println("乘法: a * b = " + (a * b));
System.out.println("除法: a / b = " + (a / b));
System.out.println("取余: a % b = " + (a % b));
// 整数溢出示例
System.out.println("\n整数溢出示例:");
int maxInt = Integer.MAX_VALUE;
System.out.println("MAX_INT = " + maxInt);
System.out.println("MAX_INT + 1 = " + (maxInt + 1)); // 溢出为最小值
// 位运算
System.out.println("\n位运算示例:");
System.out.println("a & b (AND) = " + (a & b));
System.out.println("a | b (OR) = " + (a | b));
System.out.println("a ^ b (XOR) = " + (a ^ b));
System.out.println("~a (NOT) = " + (~a));
System.out.println("a << 2 (左移) = " + (a << 2));
System.out.println("a >> 2 (右移) = " + (a >> 2));
}
// 浮点数类型操作示例
public static void floatingPointOperations() {
System.out.println("\n2. 浮点数类型操作示例:");
double x = 10.5;
double y = 3.2;
System.out.println("x = " + x + ", y = " + y);
System.out.println("加法: x + y = " + (x + y));
System.out.println("减法: x - y = " + (x - y));
System.out.println("乘法: x * y = " + (x * y));
System.out.println("除法: x / y = " + (x / y));
// 浮点数精度问题示例
System.out.println("\n浮点数精度问题示例:");
double d1 = 0.1;
double d2 = 0.2;
System.out.println("0.1 + 0.2 = " + (d1 + d2));
System.out.println("0.1 + 0.2 == 0.3? " + ((d1 + d2) == 0.3));
// 正确的浮点数比较方式
double epsilon = 0.000001; // 定义一个很小的误差范围
System.out.println("使用误差范围比较: " + (Math.abs((d1 + d2) - 0.3) < epsilon));
}
// 类型转换示例
public static void typeConversionExamples() {
System.out.println("\n3. 类型转换示例:");
// 隐式转换(自动类型提升)
int i = 10;
double d = i; // int自动转换为double
System.out.println("int " + i + " 隐式转换为 double: " + d);
// 显式转换(强制类型转换)
double pi = 3.14159;
int intPi = (int) pi; // double强制转换为int,会丢失小数部分
System.out.println("double " + pi + " 强制转换为 int: " + intPi);
// 表达式中的类型提升
System.out.println("\n表达式中的类型提升:");
int a = 10;
double b = 3.0;
System.out.println("a / b = " + (a / b) + " (int被提升为double)");
// 注意:整数除法会截断小数部分
System.out.println("10 / 4 = " + (10 / 4) + " (整数除法)");
System.out.println("10.0 / 4 = " + (10.0 / 4) + " (浮点数除法)");
}
// 使用Math类进行高级计算
public static void mathClassExamples() {
System.out.println("\n4. Math类高级计算示例:");
System.out.println("Math.sqrt(25) = " + Math.sqrt(25)); // 平方根
System.out.println("Math.pow(2, 5) = " + Math.pow(2, 5)); // 幂运算
System.out.println("Math.abs(-10.5) = " + Math.abs(-10.5)); // 绝对值
System.out.println("Math.max(10, 20) = " + Math.max(10, 20)); // 最大值
System.out.println("Math.min(10, 20) = " + Math.min(10, 20)); // 最小值
System.out.println("Math.round(3.6) = " + Math.round(3.6)); // 四舍五入
System.out.println("Math.ceil(3.2) = " + Math.ceil(3.2)); // 向上取整
System.out.println("Math.floor(3.8) = " + Math.floor(3.8)); // 向下取整
// 三角函数
System.out.println("\n三角函数示例:");
System.out.println("Math.sin(Math.PI/2) = " + Math.sin(Math.PI/2));
System.out.println("Math.cos(0) = " + Math.cos(0));
System.out.println("Math.tan(Math.PI/4) = " + Math.tan(Math.PI/4));
// 随机数
System.out.println("\n随机数示例:");
System.out.println("Math.random() = " + Math.random()); // 0.0到1.0之间的随机数
System.out.println("随机整数(1-100): " + (int)(Math.random() * 100 + 1));
}
}
bash
Java基本数据类型数学计算示例
==============================
1. 整数类型操作示例:
a = 15, b = 4
加法: a + b = 19
减法: a - b = 11
乘法: a * b = 60
除法: a / b = 3
取余: a % b = 3
整数溢出示例:
MAX_INT = 2147483647
MAX_INT + 1 = -2147483648
位运算示例:
a & b (AND) = 4
a | b (OR) = 15
a ^ b (XOR) = 11
~a (NOT) = -16
a << 2 (左移) = 60
a >> 2 (右移) = 3
2. 浮点数类型操作示例:
x = 10.5, y = 3.2
加法: x + y = 13.7
减法: x - y = 7.3
乘法: x * y = 33.6
除法: x / y = 3.28125
浮点数精度问题示例:
0.1 + 0.2 = 0.30000000000000004
0.1 + 0.2 == 0.3? false
使用误差范围比较: true
3. 类型转换示例:
int 10 隐式转换为 double: 10.0
double 3.14159 强制转换为 int: 3
表达式中的类型提升:
a / b = 3.3333333333333335 (int被提升为double)
10 / 4 = 2 (整数除法)
10.0 / 4 = 2.5 (浮点数除法)
4. Math类高级计算示例:
Math.sqrt(25) = 5.0
Math.pow(2, 5) = 32.0
Math.abs(-10.5) = 10.5
Math.max(10, 20) = 20
Math.min(10, 20) = 10
Math.round(3.6) = 4
Math.ceil(3.2) = 4.0
Math.floor(3.8) = 3.0
三角函数示例:
Math.sin(Math.PI/2) = 1.0
Math.cos(0) = 1.0
Math.tan(Math.PI/4) = 0.9999999999999999
随机数示例:
Math.random() = 0.123456789
随机整数(1-100): 42
二、包装类
基本类型 | 包装类 |
---|---|
byte |
Byte |
short |
Short |
int |
Integer |
long |
Long |
float |
Float |
double |
Double |
boolean |
Boolean |
char |
Character |
包装类的必要性:
-
用于泛型 :泛型不能使用基本类型,例如
List<Integer>
。 -
null 值 :包装类对象可以为
null
,可以表示缺失值。 -
提供工具方法 :例如
Integer.parseInt(String s)
。
java
import java.util.Arrays;
import java.util.List;
public class WrapperClassMathExamples {
public static void main(String[] args) {
// 1. 基本转换和解析
System.out.println("=== 基本转换和解析 ===");
Integer num1 = Integer.valueOf("123"); // 字符串转Integer
Double num2 = Double.parseDouble("3.14"); // 字符串转Double
System.out.println("Integer值: " + num1);
System.out.println("Double值: " + num2);
// 2. 自动装箱和拆箱
System.out.println("\n=== 自动装箱和拆箱 ===");
Integer autoBoxed = 42; // 自动装箱
int autoUnboxed = autoBoxed; // 自动拆箱
System.out.println("自动装箱: " + autoBoxed);
System.out.println("自动拆箱: " + autoUnboxed);
// 3. 数值比较
System.out.println("\n=== 数值比较 ===");
Integer a = 100;
Integer b = 200;
System.out.println("较大值: " + Integer.max(a, b));
System.out.println("较小值: " + Integer.min(a, b));
System.out.println("比较结果: " + Integer.compare(a, b));
// 4. 数学运算
System.out.println("\n=== 数学运算 ===");
System.out.println("求和: " + Integer.sum(10, 20));
System.out.println("位反转: " + Integer.reverse(10));
System.out.println("二进制表示: " + Integer.toBinaryString(10));
// 5. 类型转换
System.out.println("\n=== 类型转换 ===");
Integer intVal = 255;
System.out.println("转为double: " + intVal.doubleValue());
System.out.println("转为float: " + intVal.floatValue());
System.out.println("十六进制: " + Integer.toHexString(intVal));
// 6. 常量值
System.out.println("\n=== 常量值 ===");
System.out.println("Integer最大值: " + Integer.MAX_VALUE);
System.out.println("Integer最小值: " + Integer.MIN_VALUE);
System.out.println("Double最大值: " + Double.MAX_VALUE);
System.out.println("Double最小值: " + Double.MIN_VALUE);
// 7. 特殊值处理
System.out.println("\n=== 特殊值处理 ===");
System.out.println("是否是NaN: " + Double.isNaN(Math.sqrt(-1)));
System.out.println("是否是无限大: " + Double.isInfinite(1.0/0.0));
// 8. 列表中的数值操作
System.out.println("\n=== 列表中的数值操作 ===");
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().mapToInt(Integer::intValue).sum();
System.out.println("列表求和: " + sum);
}
}
bash
=== 基本转换和解析 ===
Integer值: 123
Double值: 3.14
=== 自动装箱和拆箱 ===
自动装箱: 42
自动拆箱: 42
=== 数值比较 ===
较大值: 200
较小值: 100
比较结果: -1
=== 数学运算 ===
求和: 30
位反转: 1342177280
二进制表示: 1010
=== 类型转换 ===
转为double: 255.0
转为float: 255.0
十六进制: ff
=== 常量值 ===
Integer最大值: 2147483647
Integer最小值: -2147483648
Double最大值: 1.7976931348623157E308
Double最小值: 4.9E-324
=== 特殊值处理 ===
是否是NaN: true
是否是无限大: true
=== 列表中的数值操作 ===
列表求和: 15
三、精确计算:BigDecimal
核心特点:
-
不可变对象 :任何运算都会产生一个新的
BigDecimal
对象。 -
任意精度:可以表示任意精度的十进制数。
-
完全控制舍入行为 :提供了多种舍入模式(
RoundingMode
)。-
RoundingMode.HALF_UP
- 四舍五入。- 对于金融计算,通常使用 2 位小数和 HALF_EVEN 舍入模式(银行家舍入法)
-
RoundingMode.CEILING
- 向正无穷大舍入 -
RoundingMode.FLOOR
- 向负无穷大舍入 -
RoundingMode.UP
- 远离零方向舍入 -
RoundingMode.DOWN
- 向零方向舍入
-
关键:永远使用 String
构造参数来创建 BigDecimal
对象!
如果使用 double
构造参数,会将固有的精度误差带进来。
java
import java.math.BigDecimal;
import java.math.RoundingMode;
public class BigDecimalExamples {
public static void main(String[] args) {
// 1. 创建 BigDecimal 对象
BigDecimal num1 = new BigDecimal("123.456");
BigDecimal num2 = new BigDecimal("78.9");
BigDecimal num3 = BigDecimal.valueOf(50.25); // 推荐使用valueOf避免精度问题
System.out.println("数字1: " + num1);
System.out.println("数字2: " + num2);
System.out.println("数字3: " + num3);
// 2. 基本算术运算
System.out.println("\n--- 基本算术运算 ---");
// 加法
BigDecimal sum = num1.add(num2);
System.out.println("加法: " + num1 + " + " + num2 + " = " + sum);
// 减法
BigDecimal difference = num1.subtract(num2);
System.out.println("减法: " + num1 + " - " + num2 + " = " + difference);
// 乘法
BigDecimal product = num1.multiply(num2);
System.out.println("乘法: " + num1 + " * " + num2 + " = " + product);
// 除法(需要指定精度和舍入模式)
BigDecimal quotient = num1.divide(num2, 4, RoundingMode.HALF_UP);
System.out.println("除法: " + num1 + " / " + num2 + " = " + quotient);
// 3. 比较操作
System.out.println("\n--- 比较操作 ---"); // 使用 compareTo() 而不是 equals() 来比较数值,因为 equals() 还会比较精度
System.out.println(num1 + " 比较 " + num2 + ": " + num1.compareTo(num2));
System.out.println(num1 + " 等于 " + num2 + "? " + num1.equals(num2));
// 4. 四舍五入和精度控制
System.out.println("\n--- 精度控制 ---");
BigDecimal pi = new BigDecimal("3.1415926535");
BigDecimal roundedPi = pi.setScale(4, RoundingMode.HALF_UP);
System.out.println("PI 四舍五入到4位小数: " + roundedPi);
// 5. 取余操作
System.out.println("\n--- 取余操作 ---");
BigDecimal remainder = num1.remainder(num2);
System.out.println(num1 + " % " + num2 + " = " + remainder);
// 6. 最大值和最小值
System.out.println("\n--- 最大值和最小值 ---");
BigDecimal max = num1.max(num2);
BigDecimal min = num1.min(num2);
System.out.println("最大值: " + max);
System.out.println("最小值: " + min);
// 7. 幂运算
System.out.println("\n--- 幂运算 ---");
BigDecimal power = num2.pow(3);
System.out.println(num2 + " 的3次方 = " + power);
// 8. 绝对值
System.out.println("\n--- 绝对值 ---");
BigDecimal negative = new BigDecimal("-123.456");
BigDecimal absolute = negative.abs();
System.out.println(negative + " 的绝对值 = " + absolute);
// 9. 科学计数法
System.out.println("\n--- 科学计数法 ---");
BigDecimal scientific = new BigDecimal("1.23456789e5");
System.out.println("科学计数法 1.23456789e5 = " + scientific);
// 10. 金融计算示例(复利计算)
System.out.println("\n--- 复利计算示例 ---");
BigDecimal principal = new BigDecimal("10000"); // 本金
BigDecimal rate = new BigDecimal("0.05"); // 年利率 5%
int years = 10; // 投资年限
// 复利公式: A = P(1 + r)^n
BigDecimal one = BigDecimal.ONE;
BigDecimal factor = one.add(rate); // (1 + r)
BigDecimal amount = principal.multiply(factor.pow(years));
System.out.println("本金: ¥" + principal);
System.out.println("年利率: " + rate.multiply(new BigDecimal("100")) + "%");
System.out.println("投资年限: " + years + "年");
System.out.println("最终金额: ¥" + amount.setScale(2, RoundingMode.HALF_UP));
}
}
四、大整数:BigInteger
如果处理超过 long
类型范围的整数,可以使用 java.math.BigInteger
。它用于表示不可变的任意精度的整数。
java
import java.math.BigInteger;
import java.util.Random;
public class BigIntegerExamples {
public static void main(String[] args) {
// 1. 创建 BigInteger 对象
BigInteger num1 = new BigInteger("12345678901234567890");
BigInteger num2 = BigInteger.valueOf(9876543210L);
BigInteger num3 = BigInteger.TEN; // 预定义常量
// 从随机数创建
Random random = new Random();
BigInteger randomNum = new BigInteger(100, random); // 100位的随机数
// 2. 基本算术运算
BigInteger sum = num1.add(num2);
BigInteger difference = num1.subtract(num2);
BigInteger product = num1.multiply(num2);
BigInteger quotient = num1.divide(num2);
BigInteger remainder = num1.remainder(num2);
// 3. 除法和余数组合操作
BigInteger[] divAndRem = num1.divideAndRemainder(num2);
System.out.println("商: " + divAndRem[0] + ", 余数: " + divAndRem[1]);
// 4. 幂运算
BigInteger power = num3.pow(20); // 10^20
// 5. 最大公约数
BigInteger gcd = num1.gcd(num2);
// 6. 模运算
BigInteger mod = num1.mod(num2);
// 模逆元 (需要模数是质数)
try {
BigInteger modInverse = num1.modInverse(num2);
} catch (ArithmeticException e) {
System.out.println("模逆元不存在: " + e.getMessage());
}
// 7. 模幂运算
BigInteger modPow = num1.modPow(BigInteger.valueOf(100), num2);
// 8. 比较操作
int comparison = num1.compareTo(num2);
if (comparison == 0) {
System.out.println("num1 等于 num2");
} else if (comparison < 0) {
System.out.println("num1 小于 num2");
} else {
System.out.println("num1 大于 num2");
}
// 9. 位操作
BigInteger shiftedLeft = num1.shiftLeft(3); // 乘以 2^3
BigInteger shiftedRight = num1.shiftRight(2); // 除以 2^2
// 10. 素数测试 (概率性测试)
boolean isPrime = num1.isProbablePrime(100); // 100是确定性参数
System.out.println("可能是素数: " + isPrime);
// 11. 下一个素数
BigInteger nextPrime = num1.nextProbablePrime();
// 12. 转换为其他类型
long longValue = num2.longValue();
int intValue = num2.intValue();
String stringValue = num1.toString();
// 13. 按不同进制输出
String binaryString = num1.toString(2); // 二进制
String hexString = num1.toString(16); // 十六进制
// 14. 绝对值
BigInteger negativeNum = new BigInteger("-1234567890");
BigInteger absValue = negativeNum.abs();
// 15. 符号检查
int sign = num1.signum(); // -1, 0, 或 1
// 16. 位长度计算
int bitLength = num1.bitLength();
// 17. 设置特定位
BigInteger setBit = num1.setBit(5); // 设置第5位为1
// 18. 清除特定位
BigInteger clearBit = num1.clearBit(5); // 设置第5位为0
// 19. 测试特定位
boolean bitTest = num1.testBit(5);
// 20. 位计数
int bitCount = num1.bitCount(); // 值为1的位数
System.out.println("所有操作完成!");
}
}
五、实际应用示例:RSA 加密算法核心计算
java
import java.math.BigInteger;
import java.util.Random;
public class RSAExample {
public static void main(String[] args) {
// 生成大素数 (简化示例,实际应用需要更大的素数)
BigInteger p = BigInteger.probablePrime(512, new Random());
BigInteger q = BigInteger.probablePrime(512, new Random());
// 计算 n = p * q
BigInteger n = p.multiply(q);
// 计算欧拉函数 φ(n) = (p-1)(q-1)
BigInteger phi = p.subtract(BigInteger.ONE)
.multiply(q.subtract(BigInteger.ONE));
// 选择公钥指数 e (通常为65537)
BigInteger e = BigInteger.valueOf(65537);
// 计算私钥指数 d = e^(-1) mod φ(n)
BigInteger d = e.modInverse(phi);
// 要加密的消息
BigInteger message = new BigInteger("123456789");
// 加密: ciphertext = message^e mod n
BigInteger ciphertext = message.modPow(e, n);
// 解密: decrypted = ciphertext^d mod n
BigInteger decrypted = ciphertext.modPow(d, n);
System.out.println("原始消息: " + message);
System.out.println("加密后: " + ciphertext);
System.out.println("解密后: " + decrypted);
System.out.println("解密成功: " + message.equals(decrypted));
}
}