赞
踩
1:有两个数组
int[] a1={123,38,103,89};
int[] b1={34,8,11,9};
求两个数组中所有的质数。
hello主函数的代码:
package my; public class Hello { public static void main(String[] args) { PrimeFilter filter = new PrimeFilter(); int[] a1 = {123, 38, 103, 89}; int[] b1 = {34, 8, 11, 29}; filter.put(a1); filter.put(b1); int[] numbers = filter.values(); for (int i = 0; i < numbers.length; i++) { System.out.println("the result:" +numbers[i]);//数组在哪里输出就在哪里遍历 } } } /*the result:103 the result:89 the result:11 the result:29 */
PrimeFilter的代码:
package my; public class PrimeFilter { public int[] result = new int[512]; public int total = 0; //用户输入数组data;把data数组里面的所有质数存在result的数组里面 public void put(int[] data) { for (int i = 0; i < data.length; i++) { if (this.isPrime(data[i])) { this.result[total] = data[i]; this.total += 1; } } } //取出最终过滤得到所有的质数 public int[] values() { int[] r = new int[total]; for (int i = 0; i < this.total; i++) { r[i] = this.result[i]; } return r; } //判断n是不是质数;true是质数,false不是质数 public boolean isPrime(int n) { for (int i = 2; i < n; i++) { if (n % i == 0) { return false; } } return true; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。