Multiplying digits of a number until you reach a one digit number - java

Assume, you input the number 546, then you should find the product of its digits, which is 546=120, then multiply the digits of 120 until and so on, continue until you get a one digit number.
Here's the code I wrote, but the loop doesn't work correctly and I've tried to fix it, but nothing changed. Could you please help me?
import java.util.*;
public class Product {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
System.out.println("Please input the number");
numberOfProducts(a);
}
public static void numberOfProducts(int n){
int product = 1;
while(n>10) {
int current = n;
while (current != 0) {
product = product * (current % 10);
current = current / 10;
n = product;
System.out.println(product);
}
}
}
}

For a different take on the solution you can use a recursive lambda
import java.util.Scanner;
import java.util.function.IntFunction;
public class Product {
// this simply reduces the number to the product of its digits.
static IntFunction<Integer> prod =
(a) -> a < 10 ? a : a % 10 * Product.prod.apply(a / 10);
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please input the number");
int n = keyboard.nextInt();
// Now continue applying the lambda until the result is < 10.
while (n > 10) {
n = prod.apply(n);
}
System.out.println(n);
}
}

I think you are looking something like the code below:
import java.util.Scanner;
public class Main {
public static int numberOfProducts(String number) {
int product = 1;
do {
for (int i = 0; i < number.length(); ++i){
// This line converts the every digit of the number string to an integer.
product *= number.charAt(i) - '0';
}
// Remove this line, if you don't want to print the product of each iteration.
System.out.println(number);
// Update number with the new product.
// This line converts the int product to a new string.
number = "" + product;
} while (product > 10);
return product;
}
public static void main(String[] args) {
System.out.print("Please input the number: ");
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
// Treat number as a string for easier indexing.
String number = "" + a;
System.out.println(numberOfProducts(number));
}
}
When the above code runs, with 546 as input, it outputs:
Please input the number: 546
546
120
0

After looking through your code, your issue seems to be in this expression:
current % 10.
The modulo operation gives you the remainder of a division by ten.
In the case of your input 120, the result of that operation would be 0.
Following the rest of your application logic, your iteration variable will be set to zero, ending your loop immediately.
I will not give you copy-paste code to fix this problem, as it seems like a programming course assignment. I will however help you solve it.
My suggested fix is to change your approach to this problem and not try to solve this the mathematical way, but rather in a way that takes advantage of the Java programing language.
You could change your input from an Integer to a String.
In which case, you can use String.length() to ensure your requirement is fulfilled when exiting the loop.
In your loop, you split the String into substrings of length 1. Afterwards, you just multiply these.
When the loop exits (because String length is no longer greater than 1) you will have your intended result.
Good luck!

Actually your code is very close to being correct, the only thing you're doing wrong is that you are not resetting the product variable between iterations. You simply need to move the int product = 1; instruction inside the outer while loop.
Also, if you want a single digit at the end, your condition should be while(n >= 10) or while(n > 9), since 10 is still 2 digits, so we need one more iteration !
Final remark: sometimes it's easier to break your code into smaller pieces. It is easier to understand and easier to test/debug ! For example you could have first created a function productOfDigits(n) that returns the result of a single iteration, and then another function productOfDigitsUntilSingleDigit(n) that repeatedly calls the previous function.

import java.util.*;
public class Product {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
int a = keyboard.nextInt();
System.out.println("Please input the number");
numberOfProducts(a);
}
public static void numberOfProducts(int n){
int product = 1;
while (n != 0) {
product = product * (n % 10);
n = n / 10;
}
if(product > 10) {
System.out.println("Intermediate result="+product);
numberOfProducts(product);
}
else
System.out.println("Final 1 digit product="+product);
}
}

function getProductUntilSingleDigit(n) {
let product = 1;
while (n > 0 || product > 9) {
if (n == 0) {
n = product;
product = 1;
}
product = product * (n % 10);
n = Math.floor(n / 10);
}
return product;
}
console.log(getProductUntilSingleDigit(546));

Related

output is not correct(Swapping the first and last digit of a number)

the output is almost correct except the first digit is not being removed.
the code should swap the first and last digit of the number for example - if the input is 756 it should give 657 as output right now the code is showing 7657 the first digit is not being removed. –
package questionsOnLoops;
import java.lang.Math;
import java.util.Scanner;
public class OSJIDS {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int n = srv.nextInt();
int temp = n; //input number
int c = 0;
int f =n; //first digit
int l; //last digit
int result;
while(temp>0) {
temp = temp/10;
c = c+1;
}
while(f>=10) {
f = f/10;
}
g = n%10;
result = (n/10)*10+f;
result = (int) ((result%Math.pow(10,c))+(g*Math.pow(10,c)));
System.out.println(result);
}
}
I do recommend making your variables a bit more descriptive, but that is an easy fix. I am guessing from your title that you want to swap the first and last digits? This method converts the numbers to strings, making appends and insertions relatively easier in this case.
import java.util.*;
import java.io.*;
class Main {
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int num = srv.nextInt();
int lastDig = num;
int firstDig = num%10;
int len = 0;
while(lastDig>9) {
lastDig/=10;
len++;
}
String ans = Integer.toString(num).substring(1, len);
ans = firstDig+ans+lastDig;
System.out.println(ans);
}
}
Let’s use your example input, 756.
This gets rid of the last digit, 6, and instead puts the first digit there:
result = (n/10)*10+f;
So now result is 757. Next you try to put the 6 where the first 7 is:
k = (int) ((result%Math.pow(10,c))+(g*Math.pow(10,c)));
This isn’t quite correct. c is 3, the number of digits. So Math.pow(10,c) equals 1000.0. But you needed to use 100 in those two places, first to get rid of the 7 and then to add the 6 there. Try subtracting 1 from c in the expression.
My suggestions for more readable code
Don’t declare a variable until you use it; inirialize each in the declaration.
Use better variable names. For example:
input rather than n
length or numberOfDigits instead of c
firstDigit instead of f
lastDigit instead of g
lastDigitReplaced instead of result
finalResult instead of k
Your code makes it quite hard to see what is exectly happening.
There are a few problems I see in your code (next to readability).
You were able to detect the first and the last number, but getting to the result seems to contain some mistakes
result = (input/10)*10+f; here you take the input (506), you divide it by 10, multiply it by 10 to abuse the the int so that your fractions are removed and restored to the original number. Then you append the first number again.
With the calculation you did above, you removed the last number, and added the first number as the last number. You are still missing the step to add the first number. It would be easier and better to just create a new number based on your calculations
Calculating the new number
You already have most of the ingredients to calculate the new number.
You already have the firstDigit and the last digit calculated. To get to the result we take the last number, and multiply it with 10 until it's in the correct position to be first.
Next we append the first number, so that it's last in our new number
finally, we add the inbetween numbers again. (you can calculate the inbetween numbers by removing the first and last number from the original input)
I've updated your code example with the above mentioned changes. I've also gave the variables a bit more clear names to indicate what they contain
public static void main(String[] args) {
Scanner srv = new Scanner(System.in);
System.out.println("Enter any number: ");
int input = srv.nextInt();
int temp = input;
int length = 0;
int firstDigit =input;
int lastDigit;
int inbetweenNumbers;
while(temp>0) {
temp = temp/10;
length = length+1;
}
while(firstDigit>=10) {
firstDigit = firstDigit/10;
}
lastDigit = input%10;
inbetweenNumbers = input - lastDigit;
inbetweenNumbers -= firstDigit * (int)Math.pow(10,length-1);
//calculating the result
int result = 0;
result += lastDigit * (int)Math.pow(10,length-1);
//Add last number (first digit of the input)
result += firstDigit;
//add the other numbers back
result+= inbetweenNumbers;
System.out.println(result+" "+length);
}

Reversing an integer in binary representation

I tried to create a code to take in a whole number in Java and output it in binary. The problem would seem that the binary is printing out backward. For instance, 6 should output as 011 but comes out as 110.
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner in =new Scanner(System. in );
userNum = in.nextInt();
binary(userNum);
System.out.print("\n");
}
private static void binary(int userNum) {
int remainder;
while (userNum <= 1) {
System.out.print(userNum);
return;
}
remainder = userNum % 2;
binary(userNum >> 1);
System.out.print(remainder);
}
}
I tried incorporating a push stack to push the remainder into a stack that I can pull later, but couldn't quite get it to land.
private static void reverse(int userNum) {
String backwards;
while (userNum >= 0) {
backwards.push(int userNum);
System.out.println(backwards);
return;
}
}
It is part of a class assignment which asks the following.
Write a program that takes in a positive integer as input, and outputs a string of 1's and 0's representing the integer in binary. For an integer x, the algorithm is:
As long as x is greater than 0
Output x % 2 (remainder is either 0 or 1)
x = x / 2
Note: The above algorithm outputs the 0's and 1's in reverse order.
Ex: If the input is:
6
the output is:
011
6 in binary is 110; the algorithm outputs the bits in reverse.
These are the tests the program applies and my results.
Input 6
Your output binary is:110
Expected output 011
Input 19
Your output 10011
Expected output 11001
Input 255
Your output 11111111
Expected output 11111111
Any help or guidance in this, I would be greatly appreciative of it.
Per the requirement and not taking into consideration of negative numbers
import java.util.Scanner;
public class LabProgram {
public static void main(String[] args) {
int userNum;
Scanner scnr = new Scanner(System.in);
userNum = scnr.nextInt();
while(userNum > 0){
System.out.print(userNum % 2);
userNum = userNum / 2;
}
System.out.print("\n");
}
}
First using predefined method then a custom one.
public class IntToBinary {
public static void main(String[] args) {
int decimalNumber = 10;
System.out.println(Integer.toBinaryString(decimalNumber));
System.out.println(convertBinary(10));
}
public static String convertBinary(int num) {
StringBuilder sb = new StringBuilder();
int binary[] = new int[40];
int index = 0;
while (num > 0) {
binary[index++] = num % 2;
num = num / 2;
}
for (int i = index - 1; i >= 0; i--) {
sb.append(binary[i]);
}
return sb.toString();
}
}
Your program appears to work fine for positive values. However it does not handle negative numbers which have their own unique binary representation known as two's complement. You could do something like the following to accommodate:
private static void binary(int userNum) {
int remainder;
// while (userNum <= 1) {
// System.out.print(userNum);
// return;
// }
if (userNum == 0) {
return;
}
// simply mask off the bit instead of dividing by two
remainder = userNum & 1;
// and shift right thru the sign bit
binary(userNum >>> 1);
System.out.print(remainder);
}
}
binary(-6));
prints
11111111111111111111111111111010
And the reason these printed out in proper order is because your routine is recursive. That is a natural behavior of printing the values stored in the stack from a recursive procedure.
import java.util.Scanner;
public class Reverse_BinaryNum {
public static void main(String[] args) {
/* Type your code here. */
Scanner scnr = new Scanner(System.in);
int inputNum;
System.out.println("Enter the Digit : ");
inputNum = scnr.nextInt();
System.out.println("The Reverse Binary for the given Digit is : ");
while (inputNum > 0) {
System.out.print(inputNum % 2);
inputNum = inputNum / 2;
}
scnr.close();
}
}

Dr.Java related to ASCII Displayer

I want to generate a sequence of numbers where: I want to compute the next number in the sequence by: (if the number is even, divide it by 2) and (if the number is odd multiply it by 3 and add 1).
I am using ASCIIPrompter and I input the starting number which is 29.
The final display should repeatedly display the number in the sequence and generate the next number based on the conjecture above. The problem with my code is "num = even" gives me an error and i dont know how to fix this error. HELP IS GREATLY APPRECIATED THANKS.
import java.awt.*; // for Color class
import static BasicIO.Formats.*; // for getCurrencyInstance, etc.
import static java.lang.Math.*; // for math constants and functions & random
import static java.awt.Color.*; // for Color constants (e.g. RED)
public class sequence {
private ASCIIDisplayer display;
private ASCIIPrompter prompt;
public sequence() {
display = new ASCIIDisplayer();
prompt = new ASCIIPrompter();
int num;
prompt.setLabel("starting Number");
num = prompt.readInt();
for (int i = 1; i <= 5; i++) {
if (num = even) {
num = num / 2;
} else {
if (num = odd) {
num = num * 3 + 1;
}
}
display.writeDouble(num);
}
display.close();
prompt.close();
}; // constructor
public static void main(String[] args) {
sequence c = new sequence();
};
}
= is an asssignment
if (num = even) {
Thats infact assigning the (undefined?) value even to variable num. Try this instead:
if (num % 2 == 0) {
And instead checking for odd in separate if you could simply use } else { - there is no third case for integers.

Boolean in Java

Prompt: You can test to see if an integer, x, is even or odd using the Boolean expression (x / 2) * 2 == x. Integers that are even make this expression true, and odd integers make the expression false. Use a for loop to iterate five times. In each iteration, request an integer from the user. Print each integer the user types, and whether it is even or odd. Keep up with the number of even and odd integers the user types, and print “Done” when finished, so the user won’t try to type another integer. Finally, print out the number of even and odd integers that were entered.
Here is the code I have so far:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter an integer.");
int x = in.nextInt();
boolean even;
for (int i = 0; i == 5; i++) {
if ((x / 2) * 2 == x) {
even = true;
System.out.println(x + " is even.");
}
if ((x / 2) * 2 != x) {
even = false;
System.out.println(x + " is odd.");
}
}
}
Not looking for a solution, just some help as to what I need to do. Really confused about the whole Boolean thing.
This seems to be like your homework.
Seems like your 'boolean even' is not even being used, I would suggest that you don't declare nor use it. Use x = x%2 to get the number if it is even or odd is better. If it is even x should be 0, if it is odd x should be 1. % is equivalent to MOD
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int x;
int even = 0; // keep tracks the number of even
int odd = 0; // keep tracks the number of odd
for (int i = 0; i < 5; i++) {
System.out.println("Enter an integer.");
x = in.nextInt();
if (x % 2 == 0) {
even++;
System.out.println(x + " is even.");
}
if (x % 2 == 1) {
odd++;
System.out.println(x + " is odd.");
}
}
System.out.println("Done");
System.out.println("Evens: " + even "\nOdds: " + odd);
}
This code should be the answer for your homework requirement. Your in.nextInt() should be inside the for loop since you need to request the user 5 times. Not only that, your loop should be < 5 as it will loop 5 times from 0, 1, 2, 3, 4
Well, your loop won't fire; i == 5 is always going to be false every time you reach the loop.
What you may want to change your loop statement to be would be:
for (int i = 0; i <= 5; i++) {
// code
}
Further, by virtue of the way Java evaluates branches, the variable even may not have been initialized. You need to instantiate it with a value.
boolean even = false;
Finally, the most straightforward way to tell if a number is even is to use the modulus operator. If it's divisible by two, it's even. Otherwise, it's odd.
if (x % 2 == 0) {
// even, do logic
} else {
// odd, do logic
}
You are missing a requirement from the assignment - that is, the ability to keep a running tally of the number of odd and even numbers, but I leave that as an exercise to the reader.
The part that you're missing is keeping track of how many even and how many odd numbers have been encountered. You'll want two separate int variables for this, which you'll declare before your main loop.
int numEvens = 0;
int numOdds = 0;
Then, in the branches where you work out whether the entered number is odd or even, you'll increment one or other of these numbers.
Lastly, at the end of your program, you can print them both out in a message.
if you want to do this with java boolean..i think this might help you
package stackOverFlow;
public class EvenOddNumber {
public boolean findEvenOdd(int num) {
if (num % 2 == 0) {
return true;
}
else {
return false;
}
}
}
import java.util.Scanner;
public class Demo {
public static void main(String[] args) {
int num;
EvenOddNumber e = new EvenOddNumber();
System.out.print("Enter a number:");
Scanner scan = new Scanner(System.in);
num = scan.nextInt();
System.out.println( num+" is even number?: " + e.findEvenOdd(num));
}
}
A simpler way to find even and odd values is to divide number by 2 and check the remainder:
if(x % 2 == 0) // remainder is 0 when divided by 2
{
//even num
}
else
{
//odd num
}

Java multiple input

UPDATED
How can you by using this method (Collatz conjecture) to find the number with the highest number of operations between, say 4 and 230.
Any guidance appreciated.
public static void main(String[] args) {
System.out.print("Enter a low integer ");
Scanner input = new Scanner(System.in);
int low = input.nextInt();
System.out.print("Enter a high integer ");
int number = input.nextInt();
maxendurance(number);
}
public static int maxendurance(int number) {
int count = 0;
System.out.print("The number " + number);
// need to loop this i suppose in relative to user input
while (number != 1) {
number = (number & 1) != 0 ? number * 3 + 1 : number >> 1;
count++;
}
System.out.println(" has endurance: " + count);
return number;
}
You will have to loop through all the numbers between low and high. Look into for-loops:
for(int number = low; number <= high; number++)
{
// do something with number
}
Somehow you will need to execute a for every number within the loop (hint: pass it in as a parameter). Then keep track of the number with the highest count.
Oh, and please name your methods more clearly than a and b - nobody will understand what they do without going through the code.
First of all, move the input out of method a:
public static void main(String[] args) {
System.out.print("Enter an integer to be checked: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
a(number);
b();
}
public static int a(int number) {
int count = 0;
System.out.print("The number " + number);
[...]
Then you can use a simple for loop to iterate between low and high:
int bestNumber = -1;
int bestScore = -1;
for (int i = low; i <= high; i++) {
int score = a(i);
if (score < bestScore) {
bestNumber = i;
bestScore = score;
}
}
The result can then be found in bestNumber.
I am going to suggest a more advanced approach, in case relevant and incase anyone comes upon this. If you are concerned about time efficiency, Memoization or Dynamic Programming can help you, especially inverse dragon recursion.
I'll give you a hint. If you need more, just comment.
Take 3 for example. One transformation T has T(3)=10. If prior you had found it takes v transformations to take 10 to 1 and you stored (10,v) in a map, then instantly you know that it takes (v+1) steps to get 3 to 1.

Categories

Resources