I've been having an issue with the following program:
public class PrimeFinder implements Runnable {
Thread go;
StringBuffer primes = new StringBuffer();
int time = 0;
public PrimeFinder() {
start();
while (primes != null) {
System.out.println(time);
try {
Thread.sleep(1000);
} catch (InterruptedException exc) {
// do nothing
}
time++;
}
}
public void start() {
if (go == null) {
go = new Thread(this);
go.start();
}
}
public void run() {
int quantity = 1_000_000;
int numPrimes = 0;
// candidate: the number than might be prime
int candidate = 2;
primes.append("\nFirst ").append(quantity).append(" primes:\n\n");
while (numPrimes < quantity) {
if (isPrime(candidate)) {
primes.append(candidate).append(" ");
numPrimes++;
}
candidate++;
}
System.out.println(primes);
primes = null;
System.out.println("\nTime elapsed: " + time + " seconds");
}
public static boolean isPrime(int checkNumber) {
double root = Math.sqrt(checkNumber);
for (int i = 2; i <= root; i++) {
if (checkNumber % i == 0) {
return false;
}
}
return true;
}
public static void main (String[] arguments) {
new PrimeFinder();
}
}
The program will count the time it takes to Print all Primes to the console.
beginning at 0 seconds to x (when the program completes)
Then will print x number of prime numbers (line 29: quantity = 1_000_000).
Then will print "Time Elapsed: x seconds
when I run the program with a smaller quantity (ex:10) it will print up to '29' (the 10th prime).
I'm assuming there is some limitation in eclipse that is preventing a large quantity of numbers from being printed to the console.
Edit: at exactly 5572 the output to the console will be cleared
this is the output:
how many primes would you like to see?
5572
0 //this is time the program has ran
First 5572 primes:
Time elapsed: 0 seconds.
when copy and pasting here the numbers carried over, so its just disappeared from the console.
Your console output is probably limited. In Eclipse, got to...
Window > Preferences > Run/Debug > Console
Uncheck the Limit console output check box.
console output was being printed on one line, added "\n" for the if statement on lines: (41-46)
if (isPrime(candidate)) {
primes.append(candidate+ "\n").append(" "); //if candidate is prime, print # then space " "
numPrimes++;
}
candidate++;
}
Now prints vertically.
Related
I am working with a program which mimics digital clock. While running it on terminal, my results are like 21:2:139 the 9 append at the end. However, on java console it print as perfect 20:59:0.
my code:
public static void myClock(int h, int m) throws Exception{
//int minutes = m;
int s = 00;
while (true) {
if(s != 60) {
System.out.print("\t\t"+h+":"+m+":"+s+"\r");
Thread.sleep(50);
s += 01;
}else {
m += 1;
s=00;
if(m==60) {
m = 00;
h += 1;
}
}
}
}
I don't know why it's happening because I am new to linux and java.
This is a homework question.
The code compiles, but in the test case, 2 is outputting as perfect, which it is not.
I cannot use an array. I cannot use Math.min() or Math.max(). Purely conditionals and loops.
My professor says I need to only test for divisors up to and including n/2 but when I do that, I still get the 2 as a perfect number.
Any help would be appreciated.
// Project2.java
import java.io.*; // BufferedReader
import java.util.*; // Scanner
public class Project2
{
public static void main (String args[]) throws Exception
{
// ALWAYS TEST FIRST TO VERIFY USER PUT REQUIRED CMD ARGS
if (args.length < 3)
{
System.out.println("\nusage: C:\\> java Project2 <input file name> <lo> <hi>\n\n");
// i.e. C:\> java Project2 P2input.txt 1 30
System.exit(0);
}
String infileName = args[0]; // i.e. L2input.txt
int lo = Integer.parseInt( args[1] ); // i.e. 1
int hi = Integer.parseInt( args[2] ); // i.e. 30
// STEP #1: OPEN THE INPUT FILE AND COMPUTE THE MIN AND MAX. NO OUTPUT STATMENTS ALLOWED
Scanner infile = new Scanner( new File(infileName) );
int min,max;
min=max=infile.nextInt(); // WE ASSUME INPUT FILE HAS AT LEAST ONE VALUE
while ( infile.hasNextInt() )
{
// YOUR CODE HERE FIND THE MIN AND MAX VALUES OF THE FILE
// USING THE LEAST POSSIBLE NUMBER OF COMPARISONS
// ASSIGN CORRECT VALUES INTO min & max INTHIS LOOP.
// MY CODE BELOW WILL FORMAT THEM TO THE SCREEN
// DO NOT WRITE ANY OUTPUT TO THE SCREEN
int number = infile.nextInt();
if ( number < min )
{
min = number;
}
else if ( number > max )
{
max = number;
}
}
System.out.format("min: %d max: %d\n",min,max); // DO NOT REMOVE OR MODIFY IN ANY WAY
// STEP #2: DO NOT MODIFY THIS BLOCK
// TEST EVERY NUMBER BETWEEN LO AND HI INCLUSIVE FOR
// BEING PRIME AND/OR BEING PERFECT
for ( int i=lo ; i<=hi ; ++i)
{
System.out.print( i );
if ( isPrime(i) ) System.out.print( " prime ");
if ( isPerfect(i) ) System.out.print( " perfect ");
System.out.println();
}
} // END MAIN
// *************** YOU FILL IN THE METHODS BELOW **********************
// RETURNs true if and only if the number passed in is perfect
static boolean isPerfect( int n )
{
int sum = 0;
for(int i = 1; i <= n/2; i ++)
{
if(n%i == 0)
{
sum += i;
}
}
if (sum == n)
{
return true;
}
else
{
return false;
}
// (just to make it compile) YOU CHANGE AS NEEDED
}
// RETURNs true if and only if the number passed in is prime
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
for(int i = 2; i <= n/2; i++)
{
if(n%i == 0)
{
return false;
}
}
return true;
}// (just to make it compile) YOU CHANGE AS NEEDED
}
OK, I found a bug, although it's not quite the bug you described.
static boolean isPrime( int n )
{
if (n < 3)
{
return false;
}
This will incorrectly list 2 as not prime, because it's less than 3.
I am trying to write a code that changes a value by either -1 or +1 depending on a random chance. It is basically a person moving through blocks. He starts from 6 and if he ends up in 1 he wins but if he ends up in 11 he loses. The final output would look something like this:
Here we go again... time for a walk!
Walked 37 blocks, and
Landed at Home
Here we go again... time for a walk!
Walked 19 blocks, and
Landed in JAIL
Here we go again... time for a walk!
Walked 13 blocks, and
Landed in JAIL
Here we go again... time for a walk!
Walked 25 blocks, and
Landed in JAIL
I have written the following code:
public class Drunk {
public int street;
public double move;
public int i;
public boolean jail;
public static void drunkWalk() {
do {
street = 6;
move = Math.random();
i++;
if (move > 0.5) {
street++;
} else {
street--;
}
} while (street != 1 && street != 11);
if ( street == 1) {
jail = false;
} else {
jail = true;
}
for (; ; ) { --- } //This is the problem. It treats it as a method.
//How can I fix this?
}
}
How about somethink like:
public static void main(String args[])
{
Drunk drunk = new Drunk();
while (true)
{
DrunkResult result = drunk.drunkWalkToJail();
System.out.println("Walked " + result.getSteps() + " blocks, and Landed at " + (result.isInJail() ? "Jail":"Home"));
}
}
public DrunkResult drunkWalkToJail()
{
int street;
int stepCount = 0;
do
{
street = 6;
double move = Math.random();
stepCount++;
if (move > 0.5)
{
street++;
}
else
{
street--;
}
}
while (street != 1 && street != 11);
return new DrunkResult(street == 11, stepCount);
}
and
public class DrunkResult
{
boolean jail = false;
int stepCount = 0;
public DrunkResult(boolean jail, int stepCount)
{
this.jail = jail;
this.stepCount = stepCount;
}
public boolean isInJail()
{
return jail;
}
public int getSteps()
{
return stepCount;
}
}
You can do walks in parallel (a group of drunk people) and process the results independent.
I'm new to multithreading. I have a program that consists of two classes: PrimeNumber and a main class. I'm trying to find all the prime numbers in a given range.
Here's my PrimeNumber class:
import java.util.ArrayList;
import java.util.concurrent.TimeUnit;
public class PrimeNumber extends Thread{
int start, end;
int threadNumber; //used to display the thread number
static ArrayList<Integer> list = new ArrayList<Integer>(1000000);
public PrimeNumber(int start, int end, int threadNumber) {
this.start = start;
this.end = end;
this.threadNumber = threadNumber;
// added code
if(list.isEmpty()){
list.add(2);
}
}
#Override
public void run(){
long startTime = System.nanoTime();
System.out.println(threadNumber + " started");
for(int i = start; i<=end;i++){
if(isPrime(i)){
list.add(i);
}
}
System.out.println(threadNumber + " has finished");
long endTime = System.nanoTime();
System.out.println("Time for thread " + threadNumber + " is " +TimeUnit.SECONDS.convert(endTime-startTime, TimeUnit.NANOSECONDS) + " seconds.");
}
//modified method
/**
* Determine whether a number is prime
* #param number
* #return true if number is prime, false otherwise
*/
public boolean isPrime(int number){
if(number == 0 || number == 1){
return false;
}
else {
int counter = 0;
while(counter<list.size()){
if(number%list.get(counter)==0){
return false;
}
counter++;
}
}
return true;
}
}
and here's my main class
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
public class MainClass {
public static void main(String[] args) throws InterruptedException{
final int maxNumberOfThreads = 3; // number of threads I want to create
final int maxNumber = 900000; // Max range for which I'm finding all the prime numbers up to it
int initialNumber = 1;
ArrayList<Thread> myList = new ArrayList<Thread>();
for(int i = 0; i < maxNumberOfThreads; i++ ){
myList.add(new PrimeNumber(initialNumber, initialNumber+ maxNumber/maxNumberOfThreads, i+1));
myList.get(i).start();
initialNumber+=maxNumber/maxNumberOfThreads;
}
for(Thread thread : myList){
thread.join();
}
try {
Collections.sort(PrimeNumber.list); // sort the list
BufferedWriter writer = new BufferedWriter(new FileWriter(new File("Primes.txt"),true));
for(int i = 0; i <PrimeNumber.list.size(); i++){
writer.write(PrimeNumber.list.get(i).toString());
//System.out.println(PrimeNumber.list.get(i));
writer.newLine();
}
writer.close();
System.out.println("Done writing to the file");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
When I run my program here's the output I get:
2 started
3 started
1 started
1 has finished
Time for thread 1 is 3 seconds.
2 has finished
Time for thread 2 is 7 seconds.
3 has finished
Time for thread 3 is 11 seconds.
Done writing to the file
Even though the threads have similar behaviors (they all calculate the prime numbers on almost identical ranges) why is the execution time different for each thread?
I've searched for quite some time but didn't find a satisfying answer. Thanks in advance.
Edit: I've added a step in my isPrime() method which improved the execution time greatly.
This loop in method isPrime performs more iterations on thread 3 than on thread 2, and more iterations on thread 2 than on thread 1, since numbers tested are different in each case:
for(int i = 2; i< number; i++)
{
if(number%i ==0){
return false;
}
}
return true;
Also, the number of primes in each of the three ranges is different, so the number of additions to the list will be different too.
I am attempting to create a recursive method that accepts an integer parameter and prints the first n squares
separated by commas, with the odd squares in descending order followed by the even squares in ascending order.
For example, if the input is 8, it should print the following output:
49, 25, 9, 1, 4, 16, 36, 64
My code so far is:
s and n have the same values initially, the only difference is that s changes as the code forwards while n doesn't change.
private static void genSquare(int s, int n) {
if (s >= 0 && s <= n) {
if (isOdd(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s - 2, n);
}
if (s == 0 || s == 1) {
genSquare(1, n);
}
if (isEven(s)) {
System.out.print(Math.pow(n, 2) + " ");
genSquare(s + 2, n);
}
}
}
I have created a while loop version of it, which works perfectly. I just don't have the recursive version working.
Sample inputs would be using the same number for s and n.
Here is the code for the loop version:
private void genLoop(int s, int n) {
if (isEven(s)) {
s--;
}
while (s <= n) {
if (s == 1) {
System.out.print(1 + " ");
s++;
} else if (isOdd(s)) {
System.out.print(s * s + " ");
s -= 2;
} else if (isEven(s)) {
System.out.print(s * s + " ");
s += 2;
}
}
}
The problem is in this statement:
if(s == 0 || s== 1)
genSquare(1,n);
This causes the method to recurse infinitely. In fact, when you get to the point where s is zero or one, you have to make sure that you DON'T call genSquare recursively.
That's enough of a hint for you to figure the rest out for yourself ... and fix any other bugs.
In addition, there's a simpler way of squaring an integer ...
void calculateSquare(int n)
{
// odds descending and even ascending
int t=n;
if(n<=0)
return;
if(n%2==1)
{
// Calculate square now and print it also
System.out.println(n*n);
calculateSquare(--n);
}
else
{
calculateSquare(--n);
System.out.println(t*t);
}
}
This would do the job.
Try the following approach:
Assume your example where n is equal to 8. The square of 8 should printed last so you probably first should do a recursive call, then print the square of the current number.
Thinking about the task for n=7 the order of things given above should be reverted for odd numbers.
Yes it is good example for recursion . Try this it helps u
public class RecursionEx {
static int no = 0;
public static void main(String[] args) {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the Number");
try
{
no = Integer.parseInt(bufferedReader.readLine());
getSquares(no,0);
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void getSquares(int number,int count)
{
if(number==1)
{
System.out.print(number);
count=1;
getSquares(number+1, count);
}
else
{
if(number%2!=0&&count==0)
{
System.out.print(number*number+",");
getSquares(number-2,0);
return;
}
if(count==0)
getSquares(number-1,0);
if(number%2==0&&count==1)
{
if(number<=no)
System.out.print(","+number*number);
if(number>=no)
return;
getSquares(number+2, count);
}
}
}
}