【发布时间】:2011-11-28 19:34:49
【问题描述】:
作为示例,我得到了一个序列接口和一个最后一个分布数字类以及方形序列类。现在我必须想出一个实现序列接口的素数序列。我想出了一个算法,但我无法实现接口或返回值。
最后一个分布类
public class LastDigitDistribution
{
private int[] counters;
// Constructs a distribution whose counters are set to zero.
public LastDigitDistribution()
{
counters = new int[10];
}
/**
Processes values from this sequence.
@param seq the sequence from which to obtain the values
@param valuesToProcess the number of values to process
*/
public void process(Sequence seq, int valuesToProcess)
{
for (int i = 1; i <= valuesToProcess; i++)
{
int value = seq.next();
int lastDigit = value % 10;
counters[lastDigit]++;
}
}
// Displays the counter values of this distribution.
public void display()
{
for (int i = 0; i < counters.length; i++)
{
System.out.println(i + ": " + counters[i]);
}
}
}
序列接口
public interface Sequence
{
int next();
}
SquareSequence 类
public class SquareSequence implements Sequence
{
private int n;
public int next()
{
n++;
return n*n;
}
随机序列类
public class RandomSequence implements Sequence
{
public int next()
{
return (int) (Integer.MAX_VALUE * Math.random());
}
}
序列的演示/测试类
public class SequenceDemo {
public static void main(String[] args)
{
LastDigitDistribution dist1 = new LastDigitDistribution();
dist1.process(new SquareSequence(), 100);
dist1.display();
System.out.println();
LastDigitDistribution dist2 = new LastDigitDistribution();
dist2.process(new RandomSequence(), 1000);
dist2.display();
}
}
现在我必须介绍一个素数序列类,这是我迄今为止提出的素数算法很好我只是不知道如何实现它并将它与这个序列相关联。
public class SquareSequence implements Sequence
{
private int n;
public int next()
{{
for (int i = 1; i < n; i++ ){
int j;
for (j=2; j<i; j++){
int k = i%j;
if (k==0){
break;
}
}
if(i == j){
System.out.print(" "+i);
}
}
return n;
}
}
}
感谢您的帮助!
【问题讨论】:
-
家庭作业?你知道如何测试素数吗?
-
我想出的算法打印出你定义的尽可能多的素数,所以我认为我不需要想出一个测试素数的代码。因为这不是问题问我的。
-
“我想出的算法可以打印出你定义的尽可能多的素数” - 该算法如何判断一个数字是否为素数并在不测试素数的情况下打印素数?