Need help writing a java program that adds multiple digits? - java

I am trying to write this java program that asks a user for a number and counts the number of digits a number has and multiplies each digit to it's decimal value. For example I enter 546: The program should say this number has 3 digits and should multiply:
5*100=500
4*10=40
1*6=6
So far this is my code: The problems I am having with this code is that it's not counting the right amount of digits. If I enter 545 it says there is only one digit, and when it goes to divides it doesn't give the right answer.
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}

The issue is that you have a set of nested for loops that both call n /= 10. It is easier to see if you indent everything:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}
}
After removing this, the code seems to work as intended, and tells you that 545 does, in fact have 3 digits. Here is the revised code:
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("Please enter a number: ");
int n = keyboard.nextInt();
int i;
for (i = 0; n > 0; i++) {
n /= 10;
System.out.println((n%100000) / 10000);
System.out.println((n%10000) / 1000);
System.out.println((n%1000) / 100);
System.out.println((n%100) / 10);
System.out.println(n%10);
}
System.out.println("Number of digits: " + i);
}

Seems like you trying to do the same task, by using arbitrary values. Instead try to incorporate some generic sort of an algorithm. Somethingy on the lines of this posted example:
public class CountDigits {
private void performTask () {
int number = 546;
int temp = number;
int digit = 0;
int counter = 1;
while ( temp != 0 ) {
digit = temp % 10;
System.out.println ( digit + " * " + getMultiplier ( counter ) + " = " + ( digit * getMultiplier ( counter ) ) );
++counter;
temp /= 10;
}
}
private int getMultiplier ( int power ) {
int value = 1;
for ( int i = 1; i < power; ++i ) {
value *= 10;
}
return value;
}
public static void main ( String[] args ) {
new CountDigits ().performTask ();
}
}
OUTPUT:
C:\Mine\java\bin>java CountDigits
9 * 1 = 9
1 * 10 = 10
1 * 100 = 100
1 * 1000 = 1000
C:\Mine\java\bin>java CountDigits
6 * 1 = 6
4 * 10 = 40
5 * 100 = 500

int n = 546;
for( int i = 0, dig = (int) Math.log10( n ) + 1; i < dig; ++i )
{
int mult = (int) Math.pow( 10, dig - i - 1 );
int a = (n / mult) % 10;
System.out.println( a + " * " + mult + " = " + (a * mult) );
}
Results in:
5 * 100 = 500
4 * 10 = 40
6 * 1 = 6

To get the number of digits in user entered value, you can get the value and check the length of the value after converting it to String. This will give you the exact length of the digit.
For example, if variable "uservalue" in the below snippet is user entered value, the output after executing the snippet, it prints the numberOfDigit as"3".
public static void main (String args[]){
int uservalue=546;
int numberOfDigit=0;
String userValueinStr=String.valueOf(uservalue);
numberOfDigit=userValueinStr.length();
System.out.println("Number of digits in user entered value is::"+numberOfDigit );
//Now as you got the no. of digits, you can go ahead and add the your logic of multiplication
}

int n = 546;
int exponent = (int) (Math.log10(n));
for (int i = exponent; i >= 0; i--) {
int displayNum = (n / (int) Math.pow(10, i)) * (int) Math.pow(10, i);
System.out.println(displayNum);
n = n - displayNum;
}
outputs
System.out﹕ 500
System.out﹕ 40
System.out﹕ 6

Related

Is this adding bases function correct?

So I have an assignment I have that I did and works most of the time however for some reason, for some values it won't work. Here is the assignment:
https://i.stack.imgur.com/h5FOK.png
Here is my code (sorry for the wall of text, please help me):
public static int findDigitSum(int num, int base, int start) {
int answer = 0;
int stat = start;
int inc = 0;
boolean act = false;
int ans = 0;
int mult = 1;
int carry = 0;
int sum = 0;
int digit = 0;
int digit2 = 0;
int if1 = 0;
int value = 0;
int x2 = 0;
for (int i = 0; i < num; i++) {
inc = i;
stat = start;
mult = 1;
carry = 0;
while (stat > 0 || inc > 0 || carry > 0) { // should loop how many times it needs to?
digit = stat % 10; // takes unit digit of start
sum = digit + inc + carry; // creates sum of unit digit, inc, and carry
System.out.println("digit, sum: " + digit + " " + sum);
System.out.println("stat, inc, carry: " + stat + " " + inc + " " + carry);
value = sum % base; // takes the new digit value (modulo of base)
carry = sum / base; // finds the carry after (for next loop)
if (inc > 9) {
carry = carry - 1;
}
answer = answer + (mult * value); // adds answer to answer (mult 10)
mult = mult * 10;
stat = stat / 10; // finds 10's digit number for next loop
inc = inc / 10; // finds 10's digit for increment number for next loop
}
System.out.println("ans: " + ans);
System.out.println("answer: " + answer);
x2 = answer;
while (x2 > 0) {
ans = ans + x2 % 10;
x2 = x2 / 10;
}
stat = stat + inc;
answer = 0;
}
return ans;
}
Basically, the question is asking on how to add bases together. I coded this but for some reason some values don't work and I honestly have no idea why. Everything seems like it should work.
For example, when num is 25, base is 5, start is 324, for the variable 'ans' it returns 194 instead of 189 (the correct one). Someone please help me with this, I really need help.
The code doesn't work as expected, although it should technically work. I don't know what's wrong.

Why is the following code not looping to print out the digits of an inputted number?

I CAN ONLY USE BASIC VARIABLE TYPES (USED IN THE CODE), NO ARRAYS, ETC.
I want this code to loop until it prints out the digits. For example, if the inputted number is 12345, I want it to Print
1
2
3
4
5
However, it only prints
1
0
0
0
0
Any inputted number can only have 5 digits.
int num = 0;
System.out.println("Enter an integer: ");
num = linput.nextInt();
int n = 5; //should be 5 digits in inputted number;
int i = num;
for (n = 5; n >= 1; n--) {
if (n > 0) {
for (int p = n; p > 1; p--) {
i = i / 10;
}
int samplei = I;
i = i - (10 * (samplei / 10));
if (i < 0) {
i = (i * -1);
}
System.out.println(i);
}
}
1 - Using nested loop for every simple problem is very bad idea. Always try to go for non nested loop.
2 - In below code i am using an array list to store all digit and then printing it backward.
3 - Below code is a general code and will work for any length(number length).
int num = 12345;
ArrayList<Integer> al = new ArrayList<Integer>();
int count = 0;
while(num != 0) {
al.add(num%10);
num = num/10;
count++;
}
for(int i = count-1; i >=0 ; i--) {
System.out.println(al.get(i));
}
Your solution seems to be unnecessarily complicated?
System.out.println( "Enter an integer: " );
int num = linput.nextInt();
("" + num).chars().forEach( c -> System.out.println( (char)c ) );
Did I miss something?
…then You may not use streams neither?
int num = linput.nextInt();
String s = ("" + num);
for( int i = 0; i < s.length(); i++ )
System.err.println( s.charAt( i ) );
…still not complicated enough?
public void printTheDigits( int n ) {
if( (n % 10) == 0 )
return;
printTheDigits( n / 10 );
System.err.println( n % 10 );
}
int num = linput.nextInt();
printTheDigits( num );

Finding total sum of loop after finding all powers of 2 below certain number

I'm new to java/programming in general and this is a homework assignment. This is what I have so far: When I run it I get the powers of 2 below the n input. example if n = 50, output is 2 + 4 + 8 + 16 + 32 + = -2
I would like the + after 32 to be gone and I don't know how to properly sum it. I would want the sum to = 62 in this case. I tried using string builder to take off the last two characters but that isn't working for me.
import java.util.Scanner;
public class Powers {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n;
System.out.print("Enter the upper limit: ");
n = scan.nextInt();
int sum = 0;
int power = 1;
for (int i = 0; i <= n; i++) {
power = 2 * power;
if (power < n && 0 < power) {
System.out.print(power + " + ");
}
sum = sum + power;
}
System.out.println(" = " + sum);
}
}
There are multiple issues here:
When reaching the upper limit you simply stop doing the output but continue doing the summation.
You use the upper limit as the number of iterations, so in case of 50 in your example, you do a sum of all values between 1 and 2^50, which is the reason why the result is negative, because the sum became larger than the maximum number an int can keep.
Concerning your question how to break a loop, there is break ;-)
Your print is always outputting a + which is why you have the + = in your output. Change the output to something like this:
if (power < n && 0 < power) {
if (i != 0) {
System.out.print(" + ");
}
System.out.print(power);
}
I've added some functionality to your code.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
System.out.println("Type number:");
Scanner scanner = new Scanner(System.in);
int n = 0;
while (n == 0) { // to ask again if "n" is zero.
n = scanner.nextInt();
}
if (n != 0) {
scanner.close(); // to prevent resource leak
int sum = 0;
int power = 1;
for (int i = 0; i < n; i++) {
power *= 2;
sum += power;
System.out.print(power + " ");
if (sum + power * 2 < 0 | i == n - 1) {
// Should we step to the next iteration?
// If next "sum" will be bigger than the max value for
// integers
// or if this iteration is the last - it will type "sum",
// break "for" cycle and go the next line of code after
// "for" cycle.
// So in this case System.out.print("+ "); won't be
// executed.
System.out.print("= " + sum);
break;
}
System.out.print("+ ");
}
}
}
}

Converting decimal to binary error

I wanted to convert decimal to binary and the following code doesn't work.
Please help me to correct the code.
package mainpackage;
import java.util.*;
class MainClass {
public MainClass() {
}
public static int binaryfinder(int n) {
int a[] = new int[8];
int i = 0;
int b = 0;
int n1 = n;
while (n1 > 0) {
a[i] = n1 % 2;
i++;
n1 = n1 / 2;
}
System.out.printf("Binary number of %d is = ", n);
for (int j = i - 1; j >= 0; j--) {
b += ((10 ^ j) * a[j]);
}
return b;
}
public static void main(String[] args) {
System.out.println("\nEnter the number to find its binary value:\n");
Scanner k = new Scanner(System.in);
int num = k.nextInt();
int inBin = binaryfinder(num);
System.out.print(inBin);
}
}
After I click RUN, it asks to enter the binary value and when I enter the value, it says, "Binary number of 0 = " No matter what I enter it always outputs "Binary number of 0 = ".
No errors are thrown.
Integer.toBinaryString(i)
this should do the trick in java
You have an endless loop, thats why your program never terminates:
while (j != 0) {
b += ((10 ^ j) * a[j]);
}
After I click RUN, it asks to enter the binary value and when I enter the value, it says, "Binary number of 0 = " No matter what I enter it always outputs "Binary number of 0 = ". No errors are thrown.
Never ending while loop
while (j != 0) {
b += ((10 ^ j) * a[j]);
}
You are changing value of n and finally after while loop :n = 0 and so the output
while (n > 0) {
a[i] = n % 2;
i++;
n = n / 2;
}
System.out.println(output);
Your program (as whole) is incorrect
Other Options:
1) Use Integer.toBinaryString()
2) Use the basic formula to convert decimal --> binary
int n = 10;
String output = "";
do {
output = (n % 2) + output; // reverse string
n = n / 2;
} while (n > 0);

find the sum of the multiples of 3 and 5 below 1000

Ok guys, so I'm doing the Project Euler challenges and I can't believe I'm stuck on the first challenge. I really can't see why I'm getting the wrong answer despite my code looking functional:
import java.util.ArrayList;
public class Multithree {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int total =0;
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}
}
for(int temp =0; temp < 1000 ; temp++){
if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println("The multiples of 3 or 5 up to 1000 are: " +total);
}
}
I'm getting the answer as 266333 and it says it's wrong...
you should use the same for loop for both to aviod double counting numbers that are multiple of both. such as 15,30...
for(int temp =0; temp < 1000 ; temp++){
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
}else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
}
In a mathematical perspective,
You did not consider about common factors between 3 and 5.Because there is double counting.
ex; number 15 ,
30 ,
45 ,
60 ,
75 ,
90 ,
105 ,
120 ,
135 ,
150 ,
165 ,
180 ,
195 ,
210 ,
225 ,
240 ,
255 ,
270 ,
285 ,
300 ,
315 ,
330 ,
345 ,
360 ,
375 ,
390 ,
405 ,
420 ,
435 ,
450 ,
465 ,
480 ,
495 ,
510 ,
525 ,
540 ,
555 ,
570 ,
585 ,
600 ,
615 ,
630 ,
645 ,
660 ,
675 ,
690 ,
705 ,
720 ,
735 ,
750 ,
765 ,
780 ,
795 ,
810 ,
825 ,
840 ,
855 ,
870 ,
885 ,
900 ,
915 ,
930 ,
945 ,
960 ,
975 ,
990 , are common factors.
total of common factors = 33165.
Your answer is 266333
Correct answer is 233168.
Your Answer - Total of common factors
266333-33165=233168.
(this is a code for getting common factors and Total of common factors )
public static void main(String[] args) {
System.out.println("The sum of the Common Factors : " + getCommonFactorSum());
}
private static int getCommonFactorSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 && i % 5 == 0) {
sum += i;
System.out.println(i);
}
}
Don't you all think instead of using loops to compute the sum of multiples, we can easily compute sum of n terms using a simple formula of Arithmetic Progression to compute sum of n terms.
I evaluated results on both using loop and formula. Loops works simply valuable to short data ranges. But when the data ranges grows more than 1010 program takes more than hours to process the result with loops. But the same evaluates the result in milliseconds when using a simple formula of Arithmetic Progression.
What we really need to do is:
Algorithm :
Compute the sum of multiples of 3 and add to sum.
Compute the sum of multiples of 5 and add to sum.
Compute the sum of multiples of 3*5 = 15 and subtract from sum.
Here is code snippet in java from my blog post CodeForWin - Project Euler 1: Multiples of 3 and 5
n--; //Since we need to compute the sum less than n.
//Check if n is more than or equal to 3 then compute sum of all divisible by
//3 and add to sum.
if(n>=3) {
totalElements = n/3;
sum += (totalElements * ( 3 + totalElements*3)) / 2;
}
//Check if n is more than or equal to 5 then compute sum of all elements
//divisible by 5 and add to sum.
if(n >= 5) {
totalElements = n/5;
sum += (totalElements * (5 + totalElements * 5)) / 2;
}
//Check if n is more than or equal to 15 then compute sum of all elements
//divisible by 15 and subtract from sum.
if(n >= 15) {
totalElements = n/15;
sum -= (totalElements * (15 + totalElements * 15)) / 2;
}
System.out.println(sum);
If you are using Java 8 you can do it in the following way:
Integer sum = IntStream.range(1, 1000) // create range
.filter(i -> i % 3 == 0 || i % 5 == 0) // filter out
.sum(); // output: 233168
To count the numbers which are divisible by both 3 and 5 twice you can
either write the above line twice or .map() the 2 * i values:
Integer sum = IntStream.range(1, 1000)
.filter(i -> i % 3 == 0 || i % 5 == 0)
.map(i -> i % 3 == 0 && i % 5 == 0 ? 2 * i : i)
.sum(); // output: 266333
How I solved this is that I took an integer value (initialized to zero) and kept on adding the incremented value of i, if its modulo with 3 or 5 gives me zero.
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
I did this several ways and several times. The fastest, cleanest and simplest way to complete the required code for Java is this:
public class MultiplesOf3And5 {
public static void main(String[] args){
System.out.println("The sum of the multiples of 3 and 5 is: " + getSum());
}
private static int getSum() {
int sum = 0;
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
return sum;
}
If anyone has a suggestion to get it down to fewer lines of code, please let me know your solution. I'm new to programming.
int count = 0;
for (int i = 1; i <= 1000 / 3; i++)
{
count = count + (i * 3);
if (i < 1000 / 5 && !(i % 3 == 0))
{
count = count + (i * 5);
}
}
Others have already pointed out the mistakes in your code, however I want to add that the modulus operator solution is not the most efficient.
A faster implementation would be something like this:
int multiply3_5(int max)
{
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3+x5-x15;
}
In this solution I had to take out multiples of 15 because, 3 and 5 have 15 as multiple so on the second loop it will add multiples of 15 that already been added in the first loop;
Solution with a time complexity of O(1)
Another even better solution (with a time complexity of O(1)) is if you take a mathematical approach.
You are trying to sum all numbers like this 3 + 6 + 9 ... 1000 and 5 + 10 + 15 +20 + ... 1000 this is the same of having 3 * (1 + 2 + 3 + 4 + … + 333) and 5 * ( 1 + 2 + 3 + 4 + ... + 200), the sum of 'n' natural number is (n * (n + 1)) (source) so you can calculate in a constant time, as it follows:
int multiply3_5(int max)
{
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
Running Example:
public class SumMultiples2And5 {
public static int multiply3_5_complexityN(int max){
int i, x3 = 0, x5 = 0, x15 = 0;
for(i = 3; i < max; i+=3) x3 += i; // Store all multiples of 3
for(i = 5; i < max; i+=5) x5 += i; // Store all multiples of 5
for(i = 15; i < max; i+=15) x15 += i; // Store all multiples 15;
return x3 + x5 - x15;
}
public static int multiply3_5_constant(int max){
int x3 = (max - 1) / 3;
int x5 = (max - 1) / 5;
int x15 = (max - 1) / 15;
int sn3 = (x3 * (x3 + 1)) / 2;
int sn5 = (x5 * (x5 + 1)) / 2;
int sn15 = (x15 * (x15 + 1)) / 2;
return (3*sn3) + (5 *sn5) - (15*sn15);
}
public static void main(String[] args) {
System.out.println(multiply3_5_complexityN(1000));
System.out.println(multiply3_5_constant(1000));
}
}
Output:
233168
233168
Just simply
public class Main
{
public static void main(String[] args) {
int sum=0;
for(int i=1;i<1000;i++){
if(i%3==0 || i%5==0){
sum+=i;
}
}
System.out.println(sum);
}
}
You are counting some numbers twice. What you have to do is add inside one for loop, and use an if-else statement where if you find multiples of 3, you do not count them in 5 as well.
if(temp % 3 == 0){
x.add(temp);
totalforthree += temp;
} else if(temp % 5 == 0){
y.add(temp);
totalforfive += temp;
}
Logics given above are showing wrong answer, because multiples of 3 & 5 are taken for calculation. There is something being missed in above logic, i.e., 15, 30, 45, 60... are the multiple of 3 and also multiple of 5. then we need to ignore such while adding.
public static void main(String[] args) {
int Sum=0, i=0, j=0;
for(i=0;i<=1000;i++)
if (i%3==0 && i<=999)
Sum=Sum+i;
for(j=0;j<=1000;j++)
if (j%5==0 && j<1000 && j*5%3!=0)
Sum=Sum+j;
System.out.println("The Sum is "+Sum);
}
Okay, so this isn't the best looking code, but it get's the job done.
public class Multiples {
public static void main(String[]args) {
int firstNumber = 3;
int secondNumber = 5;
ArrayList<Integer> numberToCheck = new ArrayList<Integer>();
ArrayList<Integer> multiples = new ArrayList<Integer>();
int sumOfMultiples = 0;
for (int i = 0; i < 1000; i++) {
numberToCheck.add(i);
if (numberToCheck.get(i) % firstNumber == 0 || numberToCheck.get(i) % secondNumber == 0) {
multiples.add(numberToCheck.get(i));
}
}
for (int i=0; i<multiples.size(); i++) {
sumOfMultiples += multiples.get(i);
}
System.out.println(multiples);
System.out.println("Sum Of Multiples: " + sumOfMultiples);
}
}
public class Solution {
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while (t>0){
int sum = 0;
int count =0;
int n = sc.nextInt();
n--;
System.out.println((n/3*(6+(n/3-1)*3))/2 + (n/5*(10+(n/5-1)*5))/2 - (n/15*(30+(n/15-1)*15))/2);
t--;
}
}
}
If number is 10 then multiple of 3 is 3,6,9 and multiple of 5 is 5,10 total sum is 33 and program gives same answer:
package com.parag;
/*
* #author Parag Satav
*/
public class MultipleAddition {
/**
* #param args
*/
public static void main( final String[] args ) {
// TODO Auto-generated method stub
ArrayList<Integer> x = new ArrayList<Integer>();
ArrayList<Integer> y = new ArrayList<Integer>();
int totalforthree = 0;
int totalforfive = 0;
int number = 8;
int total = 0;
for ( int temp = 1; temp <= number; temp++ ) {
if ( temp % 3 == 0 ) {
x.add( temp );
totalforthree += temp;
}
else if ( temp % 5 == 0 ) {
y.add( temp );
totalforfive += temp;
}
}
total = totalforfive + totalforthree;
System.out.println( "multiples of 3 : " + x );
System.out.println( "multiples of 5 : " + y );
System.out.println( "The multiples of 3 or 5 up to " + number + " are: " + total );
}
}

Categories

Resources