How can I reduce this code to use only one while loop? - java

Here's my code so far:
public class EvenOdd
{
public static void main(String[]args)
{
System.out.print("Even numbers between 50 and 100: ");
int e = 50;
while (e <= 100) {
System.out.print(" " + e);
e += 2;
}
System.out.print("\nOdd numbers between 50 and 100: ");
int i = 51;
while (i <= 100) {
System.out.print(" " + i);
i += 2;
}
}
}
How can I reduce these two while loops to just one while loop?

Store the numbers in two StringBuilders, one for the odd numbers and the other for the even numbers :
public class EvenOdd
{
public static void main(String[]args)
{
StringBuilder even = new StringBuilder();
StringBuilder odd = new StringBuilder();
int e = 50;
while (e <= 100) {
if (e%2 == 0)
even.append (" " + e);
else
odd.append (" " + e);
e++;
}
System.out.print("Even numbers between 50 and 100: " + even.toString());
System.out.print("\nOdd numbers between 50 and 100: " + odd.toString());
}
}

public static void main(String[]args)
{
StringBuilder evenString = new StringBuilder("Even numbers between 50 and 100: ");
StringBuilder oddString = new StringBuilder("Odd numbers between 50 and 100: ");
int e = 50;
while (e <= 100) {
if((e % 2) == 0)
{
evenString.append(" " + e);
}
else
{
oddString.append(" " + e);
}
e++;
}
System.out.println(evenString);
System.out.println(oddString);
}
Use a two StringBuilders to store the strings you want to display then write them out after your done looping. Each loop do modular division (%) to see if its even or odd. If the remainder is 0 then it's even if it's not then it's odd. Based on which one it is just append it to the appropriate StringBuilder.

Reducing code duplication is often a good thing. The most basic tool that Java provides are methods, so you could extract the behavior of your loop in a method and write an equivalent program:
public class EvenOdd
{
public static void main(String[]args)
{
System.out.print("Even numbers between 50 and 100: ");
printEverySecondNumber(50, 100);
System.out.print("\nOdd numbers between 50 and 100: ");
printEverySecondNumber(51, 100);
}
public static void printEverySecondNumber(int start, int end){
int current = start;
while (current <= end) {
System.out.print(" " + current);
current += 2;
}
}
}
Note that this program behaves just the same: The loop will stil get executed twice, but it is not duplicated in code.

Use lists. They print out nicely.
public class EvenOdd
{
public static void main(String[]args)
{
List<String> even = new ArrayList<String>();
List<String> odd = new ArrayList<String>();
int e = 50;
while (e <= 100) {
if (e%2 == 0)
even.add(String.valueOf(e));
else
odd.add(String.valueOf(e));
e++;
}
System.out.print("Even numbers between 50 and 100: " + even);
System.out.print("\nOdd numbers between 50 and 100: " + odd);
}
}

Here is a solution without storing numbers
public static void main(String[] args) {
int i = 0;
System.out.print("Even numbers between 50 and 100: ");
while (i <= 50) {
if (i == 26) {
System.out.print("\nOdd numbers between 50 and 100: ");
}
if (i <= 25) {
System.out.print (" " + (2 * i + 50));
} else {
System.out.print (" " + (2 * (i - 25) + 49));
}
i++;
}
}

If you are determined to do a single loop
int n = 50;
System.out.print("Even numbers between 50 and 100:");
while(n < 151){
if(n <= 100)
System.out.print(" " + n);
else
System.out.print(" " + (n-50));
if(n != 100)
n = n + 2;
else{
System.out.print("\nOdd numbers between 50 and 100:");
n = n + 1;
}
}
The benefit to this is you aren't building any unnecessary objects or having to manage anything other than n really.
If your goal is to reduce loop iterations
StringBuilder evenString = new StringBuilder();
StringBuilder oddString = new StringBuilder();
int n = 50;
while(n <= 100){
evenString.append(" " + n);
if(n != 100)
oddString = oddString.append(" " + (n + 1));
n = n + 2;
}
System.out.println("Even numbers between 50 and 100:" + evenString);
System.out.print("Odd numbers between 50 and 100:" + oddString);
Something to notice, this cuts your iterations in half over using a single while with if statements.

Just re-start iterations by re-setting the counter:
public class EvenOdd
{
public static void main(String[]args)
{
int e = 0;
while (1) {
if (e==0) {
System.out.print("Even numbers between 50 and 100:");
e = 50;
}
else
if (e==102) {
System.out.print("\nOdd numbers between 50 and 100:");
e = 51;
}
else
if (e==101) {
System.out.print("\n");
break;
}
System.out.print(" " + e);
e += 2;
}
}
}

Related

TwinPrimes on JAVA

Twin primes are a pair of prime numbers that differ by 2. For example, 3 and 5 are twin primes, 5 and
7 are twin primes, and 11 and 13 are twin primes. Write a Java program TwinPrimes.java that prompts
the user to input the search range of twin primes, display all the twin primes (2 pairs per line) within
the range, and print the number of twin primes found. The search range is assumed to be positive and
your program should repeatedly perform the same task until a sentinel value of -1 is entered.
The expected output of your program should be as follows:
Round 1:
Enter the search range: 100
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
Number of twin primes less than or equal to 100 is 8
Round 2:
Enter the search range: 150
(3,5) (5,7)
(11,13) (17,19)
(29,31) (41,43)
(59,61) (71,73)
......(Omitted)
Number of twin primes less than or equal to 200 is 15
Round 4:
Enter the search range: -1
End
I know that I am not complected the code, but I am struggling on how to print the Prime numbers in ( , ) ( , )way and how to calculate the number of twin primes show it at the end.
The below coding is what I had to do:
import java.util.Scanner;
import java.util.Random;
public class TwinPrimes {
public static void main(String[] args) {
int i = 0;
int A, B = 0, D = 0;
int num = 0;
System.out.println("Round" + " " + ++i + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
A = scn.nextInt();
{
if (A < 0)
System.out.println("End");
}
for (i = 3; i <= A; i++) {
int counter = 0;
for (num = B; num >= 1; num--) {
{
if (B % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
}
}
System.out.println("(" + i + "," + i + ")" + " " + "(" + i + "," + i + ")");
// sum Number of twin primes to
System.out.println("Number of twin primes less than or equal to " + A + " " + "is" + " ");
return;
}
}
}
package array1;
import java.io.IOException;
import java.util.Scanner;
public class Mainclass {
public static void main(String args[]) throws NumberFormatException, IOException
{
int a,k=0,line=0,count=0;
while(true)
{
System.out.println("Round" + " " + ++k + ":");
Scanner scn = new Scanner(System.in);
System.out.print("Enter the search range:");
a= scn.nextInt();
{
if (a< 0)
{
System.out.println("End");
System.exit(0);
}
}
System.out.println("The Twin Prime Numbers within the given range are : ");
for(int i=2; i<=(a-2); i++)
{
if(isPrime(i) == true && isPrime(i+2) == true)
{
System.out.print("("+i+","+(i+2)+") ");
line++;
if(line==2)
{
System.out.println();
line=0;
}
count++;
}
}
System.out.println();
System.out.println("the number of twin prime numbers less than or equal to"+a+"is"+count);
}
}
static boolean isPrime(int n) //funton for checking prime
{
int count=0;
for(int i=1; i<=n; i++)
{
if(n%i == 0)
count++;
}
if(count == 2)
return true;
else
return false;
}
}
I am struggling on how to print the Prime numbers in ( , ) ( , ) way
You may use String.format. See How to use String.format in Java?
For example, String.format("Found pair (%d,%d)", prime1, prime2);
How to calculate the number of twin primes show it at the end.
Simply keep a counter, say int counter when you're looking for the prime pairs.
import java.util.Scanner;
public class Main {
// Consider writing a helper function to check primality
public static boolean isPrime(int n) {
if (n <= 1) return false;
if (n == 2) return true;
for (int i = 2; i <= Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) {
int max_number = 100;
int counter = 0; // keep a count
for (int i = 2; i+2 < max_number; i++) {
if (isPrime(i) && isPrime(i+2)) {
counter++; // increment counter
String msg = String.format("Found pair (%d,%d)", i, i+2);
System.out.println(msg);
}
}
System.out.println("Total number of pairs is " + counter);
// Total number of pairs is 8
}
}

Java sum of EvenNumbers

It counts up to 5 and sum of 5 even numbers. I did it but it didn't work correctly(Mistake is about calculating the sum).Can you look at it ?
Here the code:
package com.java.ornekler;
public class Main {
public static void main(String[] args) {
int n = 1;
int count = 0;
int sum = 0;
do {
isEven(n);
if (!isEven(n)) {
n++;
continue;
} else {
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
}
while (n <= 10);
}
public static boolean isEven(int n) {
if ((n % 2) == 0) {
return true;
} else {
return false;
}
}
}
Output is:
2 is a even number
4 is a even number
6 is a even number
8 is a even number
10 is a even number
Sum is : 35
n++;
sum = sum + n; // here you incremented n then added to sum.
change to
sum = sum + n;
n++;
The reason why your sum is at 35 is because you increment your n one more time before you sum it together. Your total is 30 + numberOfN = 35
Your else statement should look like this
else {
System.out.println(+n + " is a even number ");
sum = sum + n;
n++; // this was above and should be here
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
When you find an odd number, you do this:
System.out.println(+n + " is a even number ");
n++;
sum = sum + n;
So, if n==4, first you bump it up so that n==5. Then you add it to sum, so sum increases by 5, not 4.
So fix this, add to sum before incrementing n.
More generally, instead of jumping up in ones, testing for even-ness, why not start on an even number, and jump up in twos?
And, rather than having a println and a break in an if within the loop, make it an exit condition of the loop, and put the println after the loop.
Along with comments above and you have duplicity statement: n++;.
Put that statement after if{}else{} block.
Revise the code as follows:
do {
isEven(n);
if (!isEven(n)) {
continue;
} else {
System.out.println(+n + " is a even number ");
sum = sum + n;
count++;
if (count == 5) {
System.out.println("Sum is : " +sum);
break;
}
}
n++;
}
while (n <= 10);
Java 8 syntax might be easier to follow using predefined functions for summing and limiting
package test.test;
import java.util.function.IntPredicate;
import java.util.stream.IntStream;
public class Snippet {
public static void main(String args[]) {
int sum = IntStream.iterate(1, i -> i + 1).limit(10).filter(isEven()).peek(Snippet::printEvenNumber).sum();
System.out.println("Sum is : " + sum);
}
private static void printEvenNumber(int i) {
System.out.println(i + " is an even number");
}
private static IntPredicate isEven() {
return i -> i % 2 == 0;
}
}

Having trouble with a while loop that gets a certain series of numbers from an input

I'm trying to half the input if it % 12 == 0, but if it isn't then you multiply it by 3 and add 1 onto the sum.
The question that I'm working off is: http://i.imgur.com/VzuPtZJ.png
With the code I have currently(which is below), if I enter 12, like in the question I start off with 6, but then the results begin to go wrong and then they go insanely wrong with values in the millions and negative millions etc.
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x >= 1)
{
if (x % 12 == 0)
x = x / 2;
else
x = 3 * x + 1;
count++;
results += + x + ", ";
if (x > max)
max = x;
}
results += "a total of " + count + " numbers in this sequence with a maximum value of " + max;
System.out.print(results);
}
}
The question says divide by two if the number is even. But you divide by 2 only when it is dividable by 12.
Change this line
(x % 12 == 0)
to
(x % 2 == 0)
And change while (x >= 1) to while (x > 1)
Here is the code you are looking for:-
import java.util.*;
public class sheet12t3
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter a number: ");
int aNumber = Integer.parseInt(in.nextLine());
hailstone(aNumber);
}
public static void hailstone(int x)
{
int count = 1;
int max = 0;
String results = "Hailstone series for the number " + x + " is ";
while (x > 1)
{
if (x % 2 == 0)
x = x / 2;
else
x = 3*x + 1;
System.out.print(x+" ");
max++;
}
}
}

Java - Factorial

I am printing the factorial of the first 10 numbers, so it is 0 - 9. The below code works for me. But I am unable to make the loop such that the factorial of 0 is within the loop too. Any advice is appreciated. Thank you.
public class fact {
public static void main(String[] args) {
System.out.println("\n\n(f) Loop to print first 10 factorial numbers");
System.out.println("\nFactorial of 0 is 1");
int fact = 1;
int index = 1;
while (index < 10)
{
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
index++;
}
}
}
How about adding an if condition in your while loop for index 0
int fact = 1;
int index = 0;
while (index < 10)
{
if(index == 0)
System.out.println("\nFactorial of 0 is 1");
else {
fact*=index;
System.out.println("Factorial of " + index + " is " + fact);
}
index++;
}
The factorial of 0 is a special case, so you are better off printing it outside the loop, just as you are doing now.
For big n numbers find factorial and its digit count .
import java.util.Scanner;
public class N_Faktorial {
public static void main(String [] args)
{
int u=1,A[]=new int[9999999];
Scanner scan =new Scanner(System.in);
System.out.print("n=");
int n=scan.nextInt();
A[1]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++) {
A[j]*=i;
}
for(int j=1;j<=n;j++)
{
if(A[j]>9)
{
A[j+1]+=A[j]/10;
A[j]%=10;
}
if(A[u+1]!=0) {
u++;
}
}
}
System.out.print(n+"! digit count:"+u+"\\n Result: \\n");
for(int i=u;i>=1;i--)
{
System.out.print(A[i]);
}
}
}
factorialList(10);
public static int factorialList(int indexMax) {
int fact = 1;
if (indexMax > 0) fact = indexMax * factorialList(indexMax - 1);
System.out.println("Factorial of " + indexMax + " is " + fact);
return fact;
}
Fn calls are less effective than loops but I bet it would be optimized to ~ the same on task of this size.
You can do like this
int fact = 1;
int index = 0;
while (index < 10)
{
fact=(index==0)?1:fact*(index);
System.out.println("Factorial of " + index + " is " + fact);
index++;
}

printing fibonacci numbers in tens line by line

i wrote a program to display fibonacci series in java but now i want the numbers in the sequence to be displayed in tens that is the first ten fibonacci numbers on one line followed by the next ten on the next line and so.....
i have been having real problems making that possible.
this is the program:
import java.util.Scanner;
import java.math.BigInteger;
class Fibonacci {
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
int number = new Scanner(System.in).nextInt();
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
for (int i = 1; i <= number; i++) {
System.out.println(fibonacciLoop(i) + " ");
}
}
public static BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}
print (don't println) each number to have them on the same line. And whenever your counter i is a multiple of 10, start a new line.
for (int i = 1; i <= number; i++) {
System.out.print(fibonacciLoop(i) + " ");
if (i % 10 == 0)
System.out.println();
}
if(i % 10 == 0)
{
System.out.println();
}
Or if you wanted to be fancy.
System.out.print(fibonacciLoop(i) + " " + (i % 10 == 0? "\n":""));
Note that your fibonaci calculation does not work due to the following for loop:
for (int x = 1; x <= number; x++){
return BigInteger.valueOf(x);
}
The follow will do what you requested:
import java.math.BigInteger;
import java.util.Scanner;
import java.util.LinkedList;
public class Test {
Test(int number) {
System.out.println("\n\nFibonacci series upto " + number + " numbers : ");
LinkedList<BigInteger> list = new LinkedList<BigInteger>();
for (int i = 1; i <= number; i++) {
list.add(fibonacciLoop(i));
if(list.size() == 10) {
printFibo(list);
list = new LinkedList<BigInteger>();
}
}
if(!list.isEmpty()) printFibo(list);
}
public static void main(String args[]) {
System.out.print("Enter number upto which Fibonacci series to print: ");
new Test(new Scanner(System.in).nextInt());
}
private void printFibo(LinkedList<BigInteger> list) {
for(BigInteger fiboNumber : list) {
System.out.print(fiboNumber + " ");
}
System.out.println("");
}
public BigInteger fibonacciLoop(int number) {
if (number == 1 || number == 2) {
return BigInteger.valueOf(1);
}
BigInteger fibonacci = BigInteger.valueOf(1);
BigInteger fibo1 = BigInteger.valueOf(1);
BigInteger fibo2 = BigInteger.valueOf(1);
for (int i = 3; i <= number; i++) {
fibonacci = fibo1.add(fibo2);
fibo1 = fibo2;
fibo2 = fibonacci;
}
return fibonacci;
}
}

Categories