Results 1 to 3 of 3
Thread: PrimeNumbers
- 07-19-2009, 12:39 AM #1
Member
- Join Date
- Jul 2009
- Posts
- 3
- Rep Power
- 0
PrimeNumbers
So this is my problem
Create a program that calculates the prime numbers from any inputted start
and end range of values (e.g. 5 and 28) and print the prime numbers in rows
of 10. Hint: Use a counter to count how many values are printed and then
print a blank line and re-initialize the counter back to 0.
and I have this:
import java.awt.*;
import hsa.Console;
public class Activity3ad
{
static Console c;
public static void main (String[] args)
{
c = new Console ();
int start, last;
c.println ("Please enter the first number");
first = c.readInt ();
c.println ("Please enter the last number");
last = c.readInt ();
boolean isPrime[];
isPrime = new boolean[last+1];
for (int i=start; i <=last; i++)
{
isPrime[i] = true;
}
for (int i=first; i<=last; i++)
{
if (isPrime[i])
{
for (int j=first*i; j<=last; j+=i)
{
isPrime[j] = false;
}
}
}
c.println ("between" + first +" and " + last + " the prime numbers are ");
for (int i=first; i<last;i++)
{
if (isPrime[i])
{
c.print (i,5);
}
}
}
}//end
I have no idea what to do to fix and what to do next...
- 07-20-2009, 10:51 PM #2
Member
- Join Date
- Jul 2009
- Location
- I live in Jacksonville, Fl
- Posts
- 4
- Rep Power
- 0
I am guessing you have another method called isPrime, so maybe your problem is there. What exactly are you having problems with? Helps to know what I am looking for.
- 07-23-2009, 10:41 AM #3
Member
- Join Date
- Jul 2009
- Posts
- 10
- Rep Power
- 0
try this code, i wrote it years ago:
Main Class:
Working Class:public static void main(String[] args) {
int start = 0;
int end = 51;
ArrayList al = PrimeNumber.extractPrime(start, end);
System.out.println("prime beetwen " + start + " and " + end + " are: ");
// loop to reveal result
for (int counter = 0; counter < al.size(); ++counter) {
System.out.println((Integer) al.get(counter));
}
}
public class PrimeNumber {
public static ArrayList extractPrime(int _start, int _end) throws IllegalArgumentException {
// validation
if (_end < _start) {
throw new IllegalArgumentException("invalid argument");
}
// validation
if ((_start < 0) || (_end < 0)) {
throw new IllegalArgumentException("invalid argument");
}
// this ArrayList contains all primary numbers
ArrayList arrayList = new ArrayList();
int factor = 0;
int counter = 0;
int number = 0;
for (number = _start; number < _end; ++number) {
if (number > 1) {
for (counter = 1; counter <= number; ++counter) {
// find the factor
if (number % counter == 0) {
++factor;
}
}
// prime number has only two factors, 1 and the number it self
if (factor == 2) {
arrayList.add(number);
}
// reset the factor
factor = 0;
}
}
return (arrayList);
}
}


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks