1. 输出1-100以内的质数
代码:
//输出1-100之间的质数
class Test12 {
public static void main(String[] args) {
//因为1既不是质数也不是合数,所以直接从2开始
for (int i = 2; i < 100; i++) {
//假定i是质数,进入循环判断
boolean b = true;
for (int j = 2; j < i; j++) {
//如果i能被某个j整除,说明不是质数
if (i % j == 0) {
b = false;
break;
}
}
//标记没被修改为false的就是质数
if (b) {
System.out.println(i + "是质数");
}
}
}
}
结果:
(单纯截结果太长了报看,截出来我的宝儿姐给各位看看)
2. 用递归求1-100的和
代码:
public class Recursion {
static int sum(int n) {
if (n == 1) {
return 1;
}
return sum(n - 1) + n;
}
public static void main(String[] args) {
System.out.println("sum:" + sum(100));
}
}
结果:
3.有条件最小值(索引法)
代码:
//练习:创建一个数组,产生8个50以内的随机整数保存其中,找能被13整除的数的最小值的索引
class Test9 {
public static void main(String[] args) {
int[] arr = new int[8];
for (int i = 0; i < arr.length; i++) {
arr[i] = (int) (Math.random() * 50);
}
for (int c : arr) {
System.out.print(c + " ");
}
System.out.println();
int minIndex = -1; //minIndex初始值用-1标记
for (int i = 0; i < arr.length; i++) {
if (arr[i] % 13 == 0) { //判断遍历的数能否被13整除
if (minIndex == -1) { //第一个能被13整除的数的下标刷给minIndex
minIndex = i;
} else {
if (arr[i] < arr[minIndex]) { //其余的数进行比较找到最小值,如果有更小的数,再次把下标刷新
minIndex = i;
}
}
}
}
if (minIndex != -1) { //如果minIndex为-1,说明没有符合条件的数,此处进行保护