implementing another class to create the first 100 prime numbers - java

ok I'm a little mind blown from an assignment i have to do. We have to implement a sequence class from wiley.com/go/javaexamples (the chapter 10 example) to make a new class called PrimeSequence and it has to right align the first 100 prime sequence numbers. I don't understand the point of implementing the other class and i did it but i know im not following the assignment rules because i dont understand what im supposed to implement from the other class and i also use nothing from the other class. I'm not sure on what i have to do
Sequence Class
public interface Sequence
{
int next();
}
PrimeSequence Class
public class PrimeSequence implements Sequence
{
public PrimeSequence()
{
}
public boolean isPrime(int x)
{
for (int start = 2; start <= Math.sqrt(x); start++)
{
if (x % start == 0)
{
return false;
}
}
return true;
}
public int next()
{
}
}
PrimeSequenceTester
public class PrimeSequenceTester {
public static void main(String[] args)
{
PrimeSequence prime = new PrimeSequence();
int currentNumber = 2;
int primesFound = 0;
while (primesFound < 100) {
if (prime.isPrime(currentNumber))
{
primesFound++;
System.out.printf("%4s",currentNumber + " ");
if (primesFound % 10 == 0)
{
System.out.println();
}
}
currentNumber++;
}
}

Here is a sample implementation using a Sieve of Eratosthenes (sieving only the odd numbers) and optimised to only sieve numbers once across multiple instances of the sequence. You need to do something a LOT simpler and just keep a track of what the current prime is and override the next() function so that when it is called you keep incrementing the value of the current prime until your isPrime() function returns true and then return that value.
import java.util.BitSet;
public class PrimeSequence implements Sequence {
private static final BitSet OddPrimeSieve = new BitSet( 8000 );
private static int MaxSievedPrime = 2;
static {
OddPrimeSieve.set(0, OddPrimeSieve.size() - 1, true );
}
private static int PrimeToIndex( final int prime ){
return (prime - 3) / 2;
}
private static int IndexToPrime( final int index ){
return 2*index + 3;
}
private static synchronized void setMaxSievedPrime( final int max ){
MaxSievedPrime = max;
for ( int index = PrimeToIndex( MaxSievedPrime ) + MaxSievedPrime;
index < OddPrimeSieve.length();
index += MaxSievedPrime )
OddPrimeSieve.set( index, false );
}
int currentPrime = 2;
#Override
public synchronized int next() {
final int current = currentPrime;
if ( current == 2 )
{
currentPrime++;
}
else
{
if ( currentPrime > MaxSievedPrime )
setMaxSievedPrime( currentPrime );
currentPrime = IndexToPrime( OddPrimeSieve.nextSetBit( PrimeToIndex( currentPrime ) + 1 ) );
}
return current;
}
public static void main( final String[] args ){
PrimeSequence p = new PrimeSequence();
for ( int i = 0; i < 100; i++ )
System.out.println( p.next() );
}
}

Related

Binary search program printing false

Hello every one i'm working on a binary search program. My algorithm is correct but when I run the program with the driver program i get back the value "false" repeated instead of a table that looks like this.
Table output(LINK)
here is my driver program and main program.
public class TestResulter {
public static void main(String[] args) {
//Resulter resulter = new Resulter();
int numberOfItems = 10000;
int item;
int a[ ] = new int[ numberOfItems ];
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem( a );
System.out.println( Resulter.binarySearch( a , item ) );
}
}
}
My main program with binarySearch algorithm.
import java.util.Random;
public class Resulter extends TestResulter {
private static class Result {
public Boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st) {
found = f;
index = ind;
steps = st;
}
#Override
public String toString() {
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static boolean binarySearch(int[] a, int item) {
int start=0, end=a.length-1;
while(end>=start) {
int mid = start + ((end - start) / 2);
if (a[mid] == item)
return true;
if (a[mid] > item)
end = mid-1;
else start = mid+1;
}
return false;
}
public static int randomitem ( int[] a ) {
int i;
Random random = new Random();
int item = random.nextInt( 10999 );
for( i = 0; i < 10000; i++ )
{
a[ i ] = random.nextInt( 10000 );
}
return item;
}
}
I want my program to have a similar output to my image from my linear search program.
Here is your code with some changes and refactoring:
public class TestResulter
{
public static void main(String[] args)
{
int numberOfItems = 10000;
int item;
int[] a = new int[numberOfItems];
fillArray(a);
for( int i = 0; i < 20; i++ )
{
item = Resulter.randomitem(a);
System.out.println(Resulter.binarySearch(a, item));
}
}
private static void fillArray(int[] a)
{
Random random = new Random();
for(int i = 0; i < a.length; i++)
a[i] = random.nextInt(10000);
Arrays.sort(a);
}
}
public class Resulter
{
private static class Result
{
public boolean found; // true if found, false if not found
public int index; // index where item was found, -1 if not found
public int steps; // number of comparisons performed
public Result(boolean f, int ind, int st)
{
found = f;
index = ind;
steps = st;
}
#Override
public String toString()
{
return "Result [found=" + found + ", index=" + index + ", steps=" + steps + "]";
}
}
public static Result binarySearch(int[] a, int item)
{
int start=0, end=a.length-1;
int stepCount = 0;
while(end>=start)
{
stepCount++;
int mid = start + ((end - start) / 2);
if(a[mid] == item)
return new Result(true, mid, stepCount);
else if(a[mid] > item)
end = mid-1;
else
start = mid+1;
}
return new Result(false, -1, stepCount);
}
public static int randomitem(int[] a)
{
return new Random().nextInt(10000);
}
}
As I see it, the main problems in your solution were:
The array was not sorted. Binary search only works on sorted arrays, therefore the Arrays.sort(a) command.
The binarySearch returned a boolean and not a Result object, which is what you wanted to print out.
You have a syntax hiccup in your main function. Change int a[] to int[] a.
Also, the logic actions performed in randomitem are likely a contributing factor. The item it returns which binarysearch uses is not pulled from the search array a, but is generated at random. Try return a[random.nestIng(a.length)];
I'm on the mobile app, so my syntax may not be perfect.

Sequence of random numbers without repeats

I am trying to do a pvp event in my game server which uses 3 zones to do it randomly. I use the following code but always is returning me the values 1 and 2 and repeated as well. I need some sequence like this for example: 3-2-1-2-1-3 or something that never repeats the same number.
int random = Rnd.get(1, 3);
if (random == 1)
{
setstartedpvpzone1(true);
}
if (random == 2)
{
setstartedpvpzone2(true);
}
if (random == 3)
{
setstartedpvpzone3(true);
}
this is what i get in rnd:
public final class Rnd
{
/**
* This class extends {#link java.util.Random} but do not compare and store atomically.<br>
* Instead it`s using a simple volatile flag to ensure reading and storing the whole 64bit seed chunk.<br>
* This implementation is much faster on parallel access, but may generate the same seed for 2 threads.
* #author Forsaiken
* #see java.util.Random
*/
public static final class NonAtomicRandom extends Random
{
private static final long serialVersionUID = 1L;
private volatile long _seed;
public NonAtomicRandom()
{
this(++SEED_UNIQUIFIER + System.nanoTime());
}
public NonAtomicRandom(final long seed)
{
setSeed(seed);
}
#Override
public final int next(final int bits)
{
return (int) ((_seed = ((_seed * MULTIPLIER) + ADDEND) & MASK) >>> (48 - bits));
}
#Override
public final void setSeed(final long seed)
{
_seed = (seed ^ MULTIPLIER) & MASK;
}
}
and rnd.get:
/**
* Gets a random integer number from min(inclusive) to max(inclusive)
* #param min The minimum value
* #param max The maximum value
* #return A random integer number from min to max
*/
public static final int get(final int min, final int max)
{
return rnd.get(min, max);
}
If all you are looking for is a random number that doesn't equal the previous one returned then the solution is much simpler:
private Random random = new Random();
private int previousZone = 0;
public int nextZone() {
int zone;
do {
zone = random.nextInt(3) + 1;
} while (zone == previousZone);
previousZone = zone; //store last "generated" zone
return zone;
}
[not tested] It is possible that it may contain some syntax errors as I am not a Java programmer.
int a=0,b=0;
while(true)
{
int random = Rnd.get(1, 3);
if(!(a==random or b==random))
{
a=b;
b=random;
break;
}
}
if (random == 1)
{
setstartedpvpzone1(true);
}
if (random == 2)
{
setstartedpvpzone2(true);
}
if (random == 3)
{
setstartedpvpzone3(true);
}
Your problem boils down to a graph traversal in which from each current zone, you only have 2 possible next zones and those choices never change. So here is how I would implement it:
public static class EventLocator{
private int currentZone;
private Random random;
private Map<Integer, int[]> locations;
private static EventLocator instance;
private EventLocator() {
}
public static EventLocator getInstance(){
if (instance == null) {
instance = new EventLocator();
}
return instance;
}
public int getNextZone(){
if (this.currentZone == 0) {//first time called
this.random = new Random();
this.locations = new HashMap<>(3);//graph <currentZone, posibleZones>
this.locations.put(1, new int[] { 2, 3 });
this.locations.put(2, new int[] { 1, 3 });
this.locations.put(3, new int[] { 1, 2 });
this.currentZone = this.random.nextInt(3) + 1;// to 1-based Zones
return currentZone;
}
int[] possibleZones = this.locations.get(this.currentZone);
int randomIndex = this.random.nextInt(2);//0 or 1 index
this.currentZone = possibleZones[randomIndex];
return this.currentZone;
}
}
You would call it like:
EventLocator eventLocator = MyProgram.EventLocator.getInstance();
System.out.println(eventLocator.getNextZone());
System.out.println(eventLocator.getNextZone());
This code never repeats any numbers, for example if you have 1,2,3 you can get a random sequence of 4 numbers, example 2,1,3.
Create an array with all numbers you need...
int[] a = {1, 2, 3};
Then select random items
for (int i=0; i<a.length; i++){
int random = Rnd.get(0, a.length);
//remove the selected item from the array
ArrayUtils.removeElement(a, random);
if (random == 1) {
setstartedpvpzone1(true);
} else if (random == 2) {
setstartedpvpzone2(true);
} else if (random == 3) {
setstartedpvpzone3(true);
}
}
private boolean _lastevent1 = false;
public boolean lastevent1()
{
return _lastevent1;
}
public void setlastevent1(boolean val)
{
_lastevent1 = val;
}
private boolean _lastevent2 = false;
public boolean lastevent2()
{
return _lastevent2;
}
public void setlastevent2(boolean val)
{
_lastevent2 = val;
}
private boolean _lastevent3 = false;
public boolean lastevent3()
{
return _lastevent3;
}
public void setlastevent3(boolean val)
{
_lastevent3 = val;
}
if (!lastevent1())
{
setlastevent3(false);
setstartedpvpzone3(false);
setstartedpvpzone1(true);
setlastevent1(true);
}
else if (!lastevent2())
{
setstartedpvpzone1(false);
setstartedpvpzone2(true);
setlastevent2(true);
}
else if (!lastevent3())
{
setlastevent1(false);
setlastevent2(false);
setstartedpvpzone2(false);
setstartedpvpzone3(true);
setlastevent3(true);
}
hello finally i fixed using booleans and i get this secuence, 1-2-3-1-2-3-1-2-3-1-2-3 , i breaked my mind with it because is very confuse this code but it work now as a charm , thanks for all to try to help me i very appreciate it, great community.

Setting up a global variable to count recursions

public class collatzpow {
public static int collatz(int n) {
StdOut.print( n + " ");
if (n == 1) return 0;
if (n% 2 == 0) return collatz(n/2);
else return collatz(3*n + 1);
}
public static void main(String[] args) {
int n= Integer.parseInt(args[0]);
StdOut.println(collatz(7));
}
}
I want to set up a global variable to count the number of time the program calls the recursion. I know with the number 7 it calls it 17 times.
I've been told it is very easy, but I'm struggling a bit with it.
Just declare a static int variable in the class scope and increment each time the method is called.
public class collatzpow {
public static int count = 0;
public static PrintStream StdOut = System.out;
public static int collatz(int n) {
++count;
StdOut.print(n + " ");
if (n == 1) return 0;
if (n % 2 == 0) return collatz(n / 2);
else return collatz(3 * n + 1);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
StdOut.println(collatz(7));
System.out.println(count);
}
}

Java recursion to find prime factors doesn't work

I am trying to get all prime factors of a number. The for loop should work until it finds the match and it should break and jump to the next if statement which checks if number is not equal to zero.
public class Factor {
public static ArrayList <Integer> HoldNum = new ArrayList();
public static void main(String[]args){
Factor object = new Factor();
object.Factor(104);
System.out.println(HoldNum.get(0));
}
public static int Factor(int number){
int new_numb = 0;
int n=0;
for( n = 1; n < 9; n++) {
if (number % n == 0) {
HoldNum.add(n);
new_numb = number/n;
break;
}
}
System.out.println(new_numb);
if(new_numb < 0) {
HoldNum.add(new_numb);
return 1;
} else {
return Factor(new_numb);
}
}
}
There are at least three errors :
As okiharaherbst wrote, your counter is not incremented.
you start your loop at 1, so yourval % 1 always equals to 0 and new_numb is always equals to your input val, so you'll loop endlessly on 104.
new_numb will never be lesser than 0.
You asked for a recursive solution. Here you go:
public class Example {
public static void main(String[] args) {
System.out.println(factors(104));
}
public static List<Integer> factors(int number) {
return factors(number, new ArrayList<Integer>());
}
private static List<Integer> factors(int number, List<Integer> primes) {
for (int prim = 2; prim <= number; prim++) {
if (number % prim == 0) {
primes.add(prim);
return factors(number / prim, primes);
}
}
return primes;
}
}
The code is not bullet-proof, it is only a quick-and-dirty example.
Java implementation...
public class PrimeFactor {
public int divisor=2;
void printPrimeFactors(int num)
{
if(num == 1)
return;
if(num%divisor!=0)
{
while(num%divisor!=0)
++divisor;
}
if(num%divisor==0){
System.out.println(divisor);
printPrimeFactors(num/divisor);
}
}
public static void main(String[] args)
{
PrimeFactor obj = new PrimeFactor();
obj.printPrimeFactors(90);
}
}

Java: check if number belongs to Fibonacci sequence

I'm supposed to write a code which checks if a given number belongs to the Fibonacci sequence. After a few hours of hard work this is what i came up with:
public class TP2 {
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 <= n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 8;
System.out.println(ehFibonacci(n));
}
}
I must be doing something wrong, because it always returns "false". Any tips on how to fix this?
You continue the loop while fib2 <= n, so when you are out of the loop, fib2 is always > n, and so it returns false.
/**
* #param args
*/
public static boolean ehFibonacci(int n) {
int fib1 = 0;
int fib2 = 1;
do {
int saveFib1 = fib1;
fib1 = fib2;
fib2 = saveFib1 + fib2;
}
while (fib2 < n);
if (fib2 == n)
return true;
else
return false;
}
public static void main(String[] args) {
int n = 5;
System.out.println(ehFibonacci(n));
}
This works. I am not sure about efficiency..but this is a foolproof program,
public class isANumberFibonacci {
public static int fibonacci(int seriesLength) {
if (seriesLength == 1 || seriesLength == 2) {
return 1;
} else {
return fibonacci(seriesLength - 1) + fibonacci(seriesLength - 2);
}
}
public static void main(String args[]) {
int number = 4101;
int i = 1;
while (i > 0) {
int fibnumber = fibonacci(i);
if (fibnumber != number) {
if (fibnumber > number) {
System.out.println("Not fib");
break;
} else {
i++;
}
} else {
System.out.println("The number is fibonacci");
break;
}
}
}
}
you can also use perfect square to check whether your number is Fibonacci or not. you can find the code and some explanation at geeksforgeeks.
you can also see stackexchange for the math behind it.
I'm a beginner but this code runs perfectly fine without any issues. Checked with test cases hopefully it'll solve your query.
public static boolean checkMember(int n) {
int x = 0;
int y = 1;
int sum = 0;
boolean isTrue = true;
for (int i = 1; i <= n; i++) {
x = y;
y = sum;
sum = x + y;
if (sum == n) {
isTrue=true;
break;
} else {
isTrue=false;
}
}
return isTrue;
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.print(checkMember(n));
}

Categories