Java: changing the order of lines with while-loop - java

I am new to programming and I would like to ask what should I do so that the final value of k will appear before the values of a, when I try to put it inside the loop it repeats the statement and when I put it before the loop, its value is 0.
System.out.printf("Input an integer: ");
int a = in.nextInt();
int k = 0;
System.out.print(a);
while(a > 1)
{
if(a % 2 == 0)
a = a / 2;
else
a = 3 * a + 1;
System.out.printf(", " + a);
k++;
}
System.out.println("\nk = " + k);
Output:
Input an integer: 10
10, 5, 16, 8, 4, 2, 1
k = 6

You could try:
System.out.printf("Input an integer: ");
int a = in.nextInt();
int k = 0;
String str_a = "";
System.out.print(a);
while(a > 1)
{
if(a % 2 == 0)
a = a / 2;
else
a = 3 * a + 1;
str_a += ", " + String.valueOf(a);
k++;
}
System.out.println("k = " + k);
System.out.println("a = " + str_a);

Related

How to print out the addition of the fibonacci sequence?

I saw this code on the internet and decided to try it myself, but I've been wondering, how do you print out the addition of the "fibonacci"?
package fibonacci;
import java.util.Scanner;
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int k, n, a = 1, b = 1;
k = 0;
System.out.println("input number: ");
n = sc.nextInt();
System.out.print("0 1 1 ");
while (k <= n) {
k = a + b;
if (k >= n) break;
System.out.print(k + " " );
a = b;
b = k;
}
System.out.println("Sum of 0 + 1 = 1");
System.out.println("Sum of 1 +" + a + " = " + b);
}
}
How can you generate an output like this:
0 1 1 2 3 5 8
0 + 1 = 1
1 + 1 = 2
1 + 2 = 3
2 + 3 = 5
3 + 5 = 8
this should answer your question:
package com.example.demo;
import java.util.Scanner;
public class Fibonaccci {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int k, n, a = 0, b = 1;
k = 0;
System.out.println("input number: ");
n = sc.nextInt();
System.out.print("0 1 ");
StringBuffer acumResults= new StringBuffer("\n");
while (k <= n) {
k = a + b;
acumResults.append(a+" + "+b+" = "+k+"\n");
System.out.print(k + " " );
if (k >= n) break;
a = b;
b = k;
}
System.out.println(acumResults);
}
}
Start a string with the initial calculation (0 + 1 = 1) and then append to it in each iteration of the loop the current calculation i.e.
System.out.print("0 1 1 ");
String addition = "0 + 1 = 1\n";
while (k <= n) {
k = a + b;
addition += a+ " + " +b + " = " + k + "\n";
if (k >= n) break;
System.out.print(k + " " );
a = b;
b = k;
}
System.out.println();
System.out.println(addition);
To produce exactly your output I would code the following:
package fibonacci;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class Fibonacci {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
int k, n, a = 1, b = 1;
k = 0;
List<Integer> numbers = new ArrayList<Integer>();
System.out.println("input number: ");
n = sc.nextInt();
System.out.print("0 1 1 ");
numbers.add(1);
numbers.add(1);
while (k <= n) {
k = a + b;
if (k >= n) break;
System.out.print(k + " " );
a = b;
b = k;
numbers.add(k);
}
// used for loop since I don't know your Java version
System.out.println();
int oldSum = 0;
for (int i= 0; i < numbers.size(); ++i) {
int element = numbers.get(k);
System.out.println oldSum + " + " + element + " = " + (oldSum + element);
oldSum += element;
}
}
}

How to count a sum of numbers multiple 2, 3, 5 and 7?

When I try to count a sum of multiple numbers I got not correct data. Instead of big results, programm shows little numbers like: SUMM OF 2 = 100. It can't be, because the last number multiple 2 is 98.
public class Array {
public static void main(String[] args){
multipleNums();
}
static void multipleNums(){
int i = 0;
int multTwo = 0;
int multThree = 0;
int multFive = 0;
int multSeven = 0;
int summTwo = 0;
int summThree = 0;
int summFive = 0;
int summSeven = 0;
for(i = 0; i <= 100; i++){
if(i == 0){
System.out.println("0 multiple 0");
}else if(i%2 == 0){
System.out.println(i + " multiple 2");
summTwo = i + multTwo;
}else if(i%3 == 0){
System.out.println(i + " multiple 3");
summThree = i + multThree;
}else if(i%5 == 0){
System.out.println(i + " multiple 5");
summFive = i + multFive;
}else if(i%7 == 0){
System.out.println(i + " multiple 7");
summSeven = i + multSeven;
} else {
System.out.println(i);
}
}
System.out.println();
System.out.println("SUMM OF 2 " + summTwo);
System.out.println("SUMM OF 3 " + summThree);
System.out.println("SUMM OF 5 " + summFive);
System.out.println("SUMM OF 7 " + summSeven);
}
}
Your always adding multTwo, multThree etc. which are 0. You should change your code to use sumXY += i
Change the line
summTwo = i + multTwo;
to
summTwo += i ;
do this for other variables, 3,5,7..

How do I terminate this loop?

"Only one while loop should be used to determine all even and odd numbers between 50 and 100."
public class EvenOdd {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 0;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i != x) || (j != y)) {
n++;
System.out.print(i + x + ", ");
i += 2;
if(i != x)
continue;
System.out.println("100");
System.out.print("\nOdd numbers between 50 and 100: ");
System.out.print((j+1) + y + ", ");
j += 2;
if(j != y)
continue;
}
}
}
The evens print fine but the odds continue on forever. This may be a dumb question, but I'm having the biggest brainfart right now, and I would really appreciate help on this.
Simply try this and let me know. It's based on your code, with just a few minor adjustments:
public class Teste4 {
public static void main(String args[]) {
int x = 50;
int y = 50;
int i = 0;
int j = 1;
int n = 0;
System.out.print("Even numbers between 50 and 100: ");
while((i < x) || (j < y)) {
if(i < x){
System.out.print(i + x + ", ");
i += 2;
continue;
}else if(i == x){
System.out.println("100");
i++;
}
if(j == 1){
System.out.print("\nOdd numbers between 50 and 100: ");
}
System.out.print(j + y + ", ");
j += 2;
}
}
}
Perhaps you should try this
int even_counter = 50;
int odd_counter=51;
System.out.println("Even numbers between 50 and 100: ");
while((even_counter < 100 ) || (odd_counter < 100)){
if(even_counter < 100){
System.out.print(even_counter+ " ");
even_counter+=2;
continue;
}
if(odd_counter < 100){
if(odd_counter == 51){
System.out.println("\nOdd numbers between 50 and 100: ");
}
System.out.print(odd_counter+ " ");
odd_counter+=2;
}
}
I'm sure this is an assignment but i'll add my 2 cents since it's solved. This one will give you an array.
final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD] = new int[((high - low) / 2)];
while(current < high){
numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));
Alternative approach ,
int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){
if (current % 2 == 0)
even = even.concat ("," + current);
else
odd = odd.concat("," + current);
current++;
}
System.out.println("Even no are : " + even);
System.out.println("Odd no are : " + odd);
I dont have a compiler now . I think this should be right :) .

Generating Pythagorean Triples using Fibonacci Sequence

I'm using the Fibonacci sequence to generate some pythagorean triples (3, 4, 5, etc) based off this page: http://en.wikipedia.org/wiki/Formulas_for_generating_Pythagorean_triples starting at "Generalized Fibonacci Sequence".
public static int fib(int n) {
if(n == 0) return 0;
if(n <= 2) return 1;
int i = 1;
int temp = 0;
while(n != 1) {
i += temp;
temp = i - temp;
n--;
}
return i;
}
public static void main(String[] args) {
int a = 4; //a(3)
int b = 3; //b(3)
int c = 5; //c(3)
for(int n = 4; n < 10; n++) {
System.out.println(a + "^2 + " + b + "^2 = " + c + "^2");
a = a + b + c;
b = fib((2 * n) - 1) - b;
c = fib(2 * n);
}
}
However, the output my program is giving me is not accurate:
4^2 + 3^2 = 5^2
12^2 + 10^2 = 21^2
43^2 + 24^2 = 55^2
122^2 + 65^2 = 144^2
331^2 + 168^2 = 377^2
876^2 + 442^2 = 987^2
What could be causing this problem? Have I been duped by Wikipedia?
#MarkDickinson pointed out that the formula required F(1) = 0 and F(2) = 1, which is different from what is widely used, where F(1) = 1 and F(2) = 1. That fixed my problem!

Addition of two very long integers

For practice, I am trying to add two very long integers by placing them in arrays and adding the corresponding elements in the arrays. However, when trying to add the carry over, I'm having problems (I.e., the carry over is the 1, that for instance, you add to the tens place when you do 199 + 199 = 398).
When doing 167 + 189 I get the right answer which is 356. However, for this very example though (199 + 199), I'm getting 288 instead of 398. My question is, why do I get an incorrect answer when I do 199 + 199, if the carry over works well when I do 167 + 189?
if (stringNumOneLength == stringNumTwoLength)
{ int answer;
int carryOver = 0;
int answerArray[] = new int[stringNumOneLength + 1];
for (int i = 1; i <= stringNumTwoLength; i = i + 1)
{
answer = Character.getNumericValue(stringNumOne.charAt(stringNumOneLength - i)) + Character.getNumericValue(stringNumTwo.charAt(stringNumTwoLength - i) + carryOver);
System.out.println(answer);
if (answer >= 10)
{
for (int j = 0; j <= 9; j = j + 1)
{
if (10 + j == answer)
{
carryOver = 1;
answer = j;
System.out.println("The carryover is " + carryOver + ".");
}
}
}
else
{
carryOver = 0;
}
answerArray[stringNumOneLength + 1 - i] = answer;
}
System.out.println(Arrays.toString(answerArray));
}
The output is the following:
[1, 9, 9]
[1, 9, 9]
18
The carryover is 1.
8
2
[0, 2, 8, 8]
You're adding the carry to the character rather than to its value:
... + Character.getNumericValue(stringNumTwo.charAt(stringNumTwoLength - i) + carryOver);
You want to move the right parent inside the +.
Note your for loop is unnecessary. This does the same thing:
if (answer >= 10)
{
answer -= 10;
carryOver = 1;
System.out.println("The carryover is 1.");
}
else ...
In case you're interested in an idiomatic solution:
public class Test {
public String add(String a, String b) {
StringBuilder r = new StringBuilder();
int carry = 0;
for (int ia = a.length() - 1, ib = b.length() - 1; ia >= 0 || ib >= 0; ia--, ib--) {
int aDigit = ia < 0 ? 0 : Character.getNumericValue(a.charAt(ia));
int bDigit = ib < 0 ? 0 : Character.getNumericValue(b.charAt(ib));
int sum = carry + aDigit + bDigit;
if (sum >= 10) {
sum -= 10;
carry = 1;
}
else {
carry = 0;
}
r.append(Character.forDigit(sum, 10));
}
if (carry > 0) {
r.append('1');
}
return r.reverse().toString();
}
public void run() {
System.out.println("789 + 89 = " + add("789", "89"));
System.out.println("12 + 128 = " + add("12", "128"));
System.out.println("999 + 999 = " + add("999", "999"));
}
public static void main(String[] args) {
new Test().run();
}
}
The parenthesis on this line:
answer = Character.getNumericValue(stringNumOne.charAt(stringNumOneLength - i)) + Character.getNumericValue(stringNumTwo.charAt(stringNumTwoLength - i) + carryOver);
are wrong. Notice how the + carryOver is within the call to Character.getNumericValue.

Categories

Resources