This program is meant to display an array and compute prime numbers between 1 and whatever the user enters. On some IDEs that "Capture Output", the list of prime numbers will not "word-wrap". Instead, it will display one VERY long line of numbers. This can be handled by inserting a "line-feed" in the display code that is activated every 15 numbers. I have no clue how to do this, my code is below.
import java.util.Scanner;
import java.text.DecimalFormat;
public class Lab11avst {
public static void main(String[] args) {
// This main method needs additions for the 100 point version.
Scanner input = new Scanner(System.in);
System.out.print("Enter the primes upper bound ====>> ");
final int MAX = input.nextInt();
boolean primes[];
primes = new boolean[MAX];
computePrimes(primes);
displayPrimes(primes);
}
public static void computePrimes(boolean primes[]) {
System.out.println("\nCOMPUTING PRIME NUMBERS");
int newLine = 15;
int multiplicator = 1;
int list[] = new int[1000];
for (int k=2; k < primes.length; k++) {
primes[k] = true;
}
for (int k=2; k < primes.length; k++)
for (int x=2*k;x<primes.length;x+=k)
primes[x] = false;
}
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k=2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
}
If you have to proceed with your current method of computing prime numbers, then you can just keep track of how many primes have been printed, and add a line break for every 15 numbers. I suggest making a slight change to your displayPrimes() method:
public static void displayPrimes(boolean primes[]) {
DecimalFormat output = new DecimalFormat("0000");
System.out.println("\n\nPRIMES BETWEEN 1 AND " + primes.length);
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (numPrimes % 15 == 0) System.out.println("");
if (primes[k]) System.out.print(output.format(k) + " ");
++numPrimes;
}
}
I use System.out.println here, which guarantees that the correct line break will be used for any platform.
However, a nicer way to approach the entire problem would be to just compute the actual prime numbers themselves, and then just iterate that array and display. Using this approach would require a complete refactor of code, maybe not what you want, and also probably too broad for a single question.
Let numPrimes indeed count the printed primes:
int numPrimes = 0;
for (int k = 2; k < primes.length; k++) {
if (primes[k]) {
if (numPrimes % 15 == 0) {
System.out.println();
}
System.out.print(output.format(k) + " ");
++numPrimes;
}
}
And \n is on Unix/Linux and MacOS, Windows uses \r\n:
System.out.println("\nCOMPUTING PRIME NUMBERS");
should be
System.out.println();
System.out.println("COMPUTING PRIME NUMBERS");
Related
import java.util.Scanner;
public class forLoopPrimeNumberSearch {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter begining value: ");
int beginingValue = input.nextInt();
System.out.print("Enter ending value: ");
int endingValue = input.nextInt();
System.out.println("Prime number between " + beginingValue+ " to "+ endingValue);
int counter = 0;
for(int i = beginingValue; i<= endingValue; i++){
if(i <=1){
continue;
}
boolean ifPrime = true;
for( int k = 2; k <= i ; k++){
//if i write the above line like this than i get the expected result for( int k =
if(i % k == 0){
ifPrime = false;
break;
}
}
if(ifPrime){
System.out.print(i + " ");
counter++;
}
}
System.out.println(" ");
System.out.println("Number count: " +counter);
}
Maybe there are many different ways to solve this problem but as a beginner, I try to implement what I have learned so far.
Here:
for( int k = 2; k <= i ; k++)
Because of this condition: k <= i You're checking k as a factor of i when k is equal to i. So you'll always find a factor, even if i is prime.
Change the condition to k < i. Or if you want your code to be a little more efficient, stop when k is greater than the square root of i.
The problem here is, your loop condition is k <= i. This will make it so that when you get to the last iteration of the loop, you check "is i divisible by i?", which of course will yield a result of a composite number. What you want to do is check all of the numbers less than i, or to be more precise less than the square root of k, to really check the primality of the number. Your loop will then become like so.
boolean ifPrime = true;
for(int k = 2; k <= Math.sqrt(i); k++) {
if(i % k == 0) {
ifPrime = false;
break;
}
}
Also, for this type of algorithm where you have to find all of the prime numbers in a certain range, something like the Sieve of Eratosthenes algorithm will work much better and will be faster.
I seriously need help please
1=1, 1+2=3, 1+2+3=6, 1+2+3+4=10
I don't know how to code the equation part
import java.util.Scanner;
public class Equations {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println ("Enter a number between 1 to 15: ");
int num = scan.nextInt();
int total = 0;
int save;
for(int i=1;i<=num;i++)
{
for(int j=1;j<=num;j++)
{
save = total+i;
i++;
}
System.out.print (save+"="+total);
System.out.println ();
}
}
This is all I have, and it doesn't work.
There are quite a few things off. You're not resetting total or save after each equation. save is an int, so it can't hold the equation string. j needs to increment to i, not num. total is never incremented. i++ doesn't belong in the inner loop.
Here's a simple, correct version:
for (int i = 1; i <= num; i++) {
int sum = 0;
String equation = "";
for (int j = 1; j <= i; j++) {
sum += j;
equation += "+" + j;
}
System.out.println(equation.substring(1) + "=" + sum);
}
A run is a sequence of adjacent repeated values . Write a program that generates a sequence of random die tosses and that prints the die values, marking only the longest run. The program should take as input the total number of die tosses (ex 10), then print:
1 6 6 3 (2 2 2 2 2) 5 2
Im quite confused on how to compare each number in order to get the correct output. Maybe using an array to store the values. Any answers or input will be of help thank you!
import java.util.Random;
import java.util.Scanner;
public class Dice
{
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount()
{
int count;
int sides = 6;
int number;
System.out.println("How many die? ");
count = keyboard.nextInt();
for(int i=0; i < count; i++)
{
number = generator.nextInt(sides);
System.out.print(number);
}
}
}
First, replace int number; with int[] numbers = new int[count];. Next, replace number = ... with numbers[i] = ....
This will give you an array of random numbers (don't print them yet!). As you generate your numbers, note how many equal numbers you get in a row (add a special counter for that). Also add variable that stores the length of the longest run so far. Every time you get a number that's equal to the prior number, increment the counter; otherwise, compare the counter to the max, change the max if necessary, and set the counter to 1. When you update the max, mark the position where the run starts (you can tell from the current position and the length of the run).
Now it's time to detect the longest run: go through the numbers array, and put an opening parenthesis where the run starts. Put a closing parenthesis when you reach the end of the run, and finish the printing to complete the output for the assignment.
import java.util.Random;
import java.util.Scanner;
public class Dice {
Random generator = new Random();
Scanner keyboard = new Scanner(System.in);
public void DiceCount() {
int sides = 6;
System.out.println("How many die? ");
int count = keyboard.nextInt();
int[] array = new int[count];
int longestLength = 1, currentLength = 1, longestLengthIndex = 0, currentLengthIndex = 1;
int currentNum = -1;
for (int i = 0; i < count; i++) {
array[i] = generator.nextInt(sides);
System.out.print(array[i] + " ");
if (currentNum == array[i]) {
currentLength++;
if (currentLength > longestLength) {
longestLengthIndex = currentLengthIndex;
longestLength = currentLength;
}
} else {
currentLength = 1;
currentLengthIndex = i;
}
currentNum = array[i];
}
System.out.println();
for (int i = 0; i < count; i++)
System.out.print((i == longestLengthIndex ? "(" : "") + array[i] + (i == (longestLengthIndex + longestLength - 1) ? ") " : " "));
}
}
Note: this will only take the first longest range. So if you have 1123335666 it will do 112(333)5666.
If you need 112(333)5(666) or 1123335(666) then I leave that to you. It's very trivial.
import java.util.Random;
public class Dice {
public static void main(String[] args) {
//make rolls
Random rand = new Random();
int[] array = new int[20];
int longestRun = 1;
int currentRun = 1;
int longestRunStart = 0;
int currentRunStart = 1;
System.out.print("Generated array: \n");
for (int i = 0; i < array.length; i++) {
array[i] = rand.nextInt(6); //add random number
System.out.print(array[i] + " "); //print array
if (i != 0 && array[i - 1] == array[i]) {
//if new number equals last number...
currentRun++; //record current run
if (currentRun > longestRun) {
longestRunStart = currentRunStart; //set index to newest run
longestRun = currentRun; //set above record to current run
}
} else {
//if new number is different from the last number...
currentRun = 1; //reset the current run length
currentRunStart = i; //reset the current run start index
}
}
//record results
System.out.print("\nIdentifying longest run: \n");
for (int i = 0; i < longestRunStart; i++) { System.out.print(array[i] + " "); } //prints all numbers leading up to the run
System.out.print("( "); //start parentheses
for (int i = longestRunStart; i < (longestRunStart + longestRun); i++) { System.out.print(array[i] + " "); } //prints the run itself
System.out.print(") "); //end parentheses
for (int i = (longestRunStart + longestRun); i < 20; i++) { System.out.print(array[i] + " "); } //all remaining numbers
}
}```
I am trying to solve this exercise, It seems easy this, but I can not understand the contraints -rules, It says:
the number may be represented on one or two hands;
if the number is represented on two hands, the larger number is given first
The rule number 2 I can not understand for example if it says 3, I have 3, 2+1, 1+2 (this not because its repeated), if it says 6 we have 6, 5+1, 4+2, 3+3, 2+4 + 1+5 but the correct output is 3, can someone guide me in this problem?? for 7 is 2, and 8 is 2, 9 is 1, and 10 is 1.
this is my code:
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= tot; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}
Its simple - if you are going to give the number using both the hands (2 hands) then you will first need to give the larger number which comprises the overall number -
eg for 7 (4+3 OR 5+2) when represented using 2 hands - give 4 first !
other option for 7 (3+4, 2+5) are invalid since it will make us to list the smaller number first which violates the rule #2
The number of the second hand must always be less than or equal to the number of the first hand. I believe the code below will work.
import java.util.Scanner;
class j1 {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int tot = 5;
int n = sc.nextInt();
int sum = 0;
int count = 1;
for (int i = 1; i <= tot; i++) {
for (int j = 1; j <= i; j++) {
sum = i + j;
if (sum == n) {
System.out.println(i);
System.out.println(j);
count++;
}
}
}
System.out.println(count);
sc.close();
}
}
I have this program that returns a factorial of N. For example, when entering 4,,, it will give 1! , 2! , 3!
How could I convert this to use nested loops?
public class OneForLoop
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for(int i = 1; i < N; i++)
{
factorial *= i;
System.out.println(i + "! = " + factorial);
}
}
}
If written as nested loops it would look like this:
for (int i = 1; i < N; ++i)
{
int factorial = 1;
for (int j = 1; j <= i; ++j) {
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
Result:
Enter a number : 10
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120
6! = 720
7! = 5040
8! = 40320
9! = 362880
This program gives the same result as yours, it just takes longer to do so. What you have already is fine. Note also that the factorial function grows very quickly so an int will be too small to hold the result for even moderately large N.
If you want to include 10! in the result you need to change the condition for i < N to i <= N.
Right now you are calculating your factorial incrementally. Just recalculate it from scratch every time. Be advised that what you have now is better than what I'm posting, but this does follow your requirements.
public class TwoForLoops
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter a number : ");
int N = input.nextInt();
int factorial = 1;
for (int i = 1; i < N; ++i)
{
factorial = 1;
for(int j = 1; j <= i; j++)
{
factorial *= j;
}
System.out.println(i + "! = " + factorial);
}
}
}
Rather than just computing everything in a linear fashion, you could consider an inner loop which would do something like what you have in the outer loop. Is that what you are trying to achieve?
Would you consider recursion a nested loop?
public long factorial(int n)
{
if (n <= 1)
return 1;
else
return n * factorial(n - 1);
}
public static void main(String [] args)
{
//print factorials of numbers 1 to 10
for(int i = 1; i <= 10; i++)
System.out.println(factorial(i));
}