sum of digits till the sum is one-digit number - java

I am a beginner java and trying to solve tricky problem
input=777
output should be 3
7+7+7=21 , 2+1=3;
From the above code if my input is 333 I am getting 9 as answer but when the sum is two digits(777=21) i am getting blank!
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum=0;
String s;
char []ch;
do
{
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(sum);
}
y=sum;
}while(ch.length>1);
}

your code maybe loop forever
the right solution is the following below
public static void main(String[] args) throws ParseException {
int y = 777;// if y is 777 i am getting blank
int sum = 0;
String s;
char[] ch;
do {
sum = 0;
s = String.valueOf(y);
ch = s.toCharArray();
if (ch.length > 1) {
for (int i = 0; i < ch.length; i++) {
sum += Character.getNumericValue(ch[i]);
}
} else {
System.out.println(ch[0]);
break;
}
y = sum;
} while (ch.length > 1);
}
Maybe the better choice is the following code
public static void main(String[] args) throws ParseException {
int y = 333;// if y is 777 i am getting blank
int sum = 0;
while (y % 10 != 0) {
sum += y %10;
y = y / 10;
if (0 == y && sum >= 10) {
y = sum;
sum = 0;
}
}
System.out.println(sum);
}
hope that helped

For a task like this, it is best practise to use recursion.
The workflow in pseudocode would look like this:
procedure sumTillOneDigit(n)
split n into it's digits
s := sum of all digits of n
if s has more than one digit:
sumTillOneDigit(s)
else
output s
I am intentionally writing this in pseudocode, since this should help you solving the task. I will not give you a Java implementation, as it looks like a homework to me.
For more information see:
https://en.wikipedia.org/wiki/Recursion_(computer_science)
http://introcs.cs.princeton.edu/java/23recursion/

You are getting that because you put the print statement in else condition..
Also note that to reset your sum value before reusing it. I.e. Set sum=0 at the start of do loop.
EDIT : there are two solutions to print you value
1. Don't put you print statements inside else conditions
Print sum outside the do while loop

First of all you must reset the value of sum variable.
and secondly you must print s in else condition and not the sum and rest is fine.
public static void main(String[] args)
{
int y=333;//if y is 777 i am getting blank
int sum;
String s;
char []ch;
do
{
sum=0;
s=String.valueOf(y);
ch=s.toCharArray();
if(ch.length>1)
{
for(int i=0;i<ch.length;i++)
{
sum+=Character.getNumericValue(ch[i]);
}
}
else
{
System.out.println(s);
}
y=sum;
}while(ch.length>1);
}

I think your solution has wrong basics. There is no point to convert your number to String and handle this as char array. You are doing too much unnecessary operations.
You can do is simpler if you stick with numbers.
You can do it using recursion:
public static int sumRec(int number){
if (number<10){
return number;
}
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
return sumRec(sum);
}
or itteration
public static int sumIt(int number){
while(number>=10){
int sum = 0;
while(number!=0){
sum += number %10;
number /= 10;
}
number = sum;
}
return number;
}
it is much simpler, right?

You can solve this by 1 line:
public static int sumDigits(int n) {
return (1 + ((n-1) % 9);
}
For example: input 777--> return 1 + ( (777-1) % 9) = 3
Also can work with negative number.

Recursive variant
public static int myFunction(int num){
if(num/10 == 0){
return num;
}
int digitSum = num%10 + myFunction(num/10);
if(digitSum/10 == 0){
return digitSum;
}
return myFunction(digitSum);
}

public static int sum_of_digits(int n) {
return --n % 9 + 1;
}

Related

Error in calculating sum of even place digits and odd place digits in java

In our directions, we have to get a 16 digit number, then sum all the digits in the odd place from right to left. After that, we have to sum all the even place digits from right to left, double the sum, then take module 9. When I try to run my code, I keep getting "Invalid", even if it is with a valid credit card number.
public static boolean validateCreditCard(long number) {
double cardSum = 0;
for (int i = 0; i < 16; i++) {
long cardnumber = (long) Math.pow(10, i);
double oddPlaceSum = 0;
double evenPlaceSum = 0;
if (i % 2 != 0) {
oddPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i))));
} else { // so if i%2 ==0
evenPlaceSum += ((int)(number % cardnumber / (Math.pow(10, i)) * 2 % 9));
}
cardSum += evenPlaceSum + oddPlaceSum;
}
if (cardSum % 10 == 0) {
return true;
System.out.println("Valid");
} else {
return false;
System.out.println("Invalid");
}
}
Try this instead :
Convert the 16 digit number into a String using Long.toString(number).
Iterate through the String character by character and keep track of even and odd indexes.
Convert each char to an Integer using Integer.valueOf() thereby adding them incrementally.
Voila, you got your evenSum and oddSum. Next steps should be trivial.
public static boolean validateCreditCard(long number){
String x = Long.toString(number);
int evenSum = 0;
int oddSum = 0;
for(int i=0; i<x.length; i=i+2) {
oddSum += Integer.valueOf(s[i]);
evenSum += Integer.valueOf(s[i+1]);
}
//Do the next steps with odd and even sums.
Also, do handle IndexOutOfBoundsException as appropriate.
You can do it in a single while loop as digits are fixed, like this:
int digit,evensum,oddsum;
int i=16;
while(i > 0){
digit=number%10;
if(i%2 == 0)
evensum+=digit;
else
oddsum+=digit;
i--;
digit/=10;
}
Try this instead
using Recusion find sum of even placed of digit and sum of odd placed of digit.
class Recursion {
static int count = 0;
static int even =0;
static int odd =0;
public static int Digits(int num) {
if (num > 0) {
count++;
if(count%2 == 0){
even += num%10;
}
else{
odd += num%10;
}
Digits(num / 10);
}
return even;
// for odd
// return odd;
}
public static void main(String[] args) {
int num = 31593;
int res = Digits(num);
System.out.println("Total digits are: " + res);
}
}
Help me How to print both even and odd sum together?

Number trailing zeros in factorial in java

import java.util.Scanner;
import java.io.*;
class factorial {
void fact(int a) {
int i;
int ar[] = new int[10000];
int fact = 1, count = 0;
for (i = 1; i <= a; i++) {
fact = fact * i;
}
String str1 = Integer.toString(fact);
int len = str1.length();
i = 0;
do {
ar[i] = fact % 10;
fact /= 10;
i++;
} while (fact != 0);
for (i = 0; i < len; i++) {
if (ar[i] == 0) {
count = count + 1;
}
}
System.out.println(count);
}
public static void main(String...ab) {
int a;
Scanner input = new Scanner(System.in);
a = input.nextInt();
factorial ob = new factorial();
ob.fact(a);
}
}
This code is work up to a = 10 but after enter number larger then a = 16 it gives wrong answer.
Please help.
As I am not able to post this question if I dont add more info for this question but I assume that the info I provide above is enough to under stand what I want.
Like many of these mathematical puzzles, you are expected to simplify the problem to make it practical. You need to find how many powers of ten in a factorial, not calculate a factorial and then find the number of trailing zeros.
The simplest solution is to count the number of powers of five. The reason you only need to count powers of five is that there is plenty of even numbers in between then to make a 10. For example, 5! has one 0, 10! has 2, 15! has three, 20! has four, and 25! has not five but six as 25 = 5 * 5.
In short you only need calculate the number of powers of five between 1 and N.
// floor(N/5) + floor(N/25) + floor(N/125) + floor(N/625) ...
public static long powersOfTenForFactorial(long n) {
long sum = 0;
while (n >= 5) {
n /= 5;
sum += n;
}
return sum;
}
Note: This will calculate the trailing zeros of Long.MAX_VALUE! in a faction of a second, whereas trying this with BigInteger wouldn't fit, no matter how much memory you had.
Please Note, this is not the mathematical solution as others suggested, this is just a refactoring of what he had initially...
Here I just used BigInteger in place of Int, and simplified your code abit. Your solution is still not optimal. I thought I would just show you what a refactored version of what you posted may look like. Also there was a bug in your initial function. It returned the number of zeros in the whole number instead of just the number of trailing zeros.
import java.math.BigInteger;
import java.util.Scanner;
class factorial {
public static void main(String... ab) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
fact(a);
}
private static void fact(int a) {
BigInteger fact = BigInteger.ONE;
int i, count = 0;
for (i = 1; i <= a; i++) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
String str1 = fact.toString();
for(int j = str1.length() - 1; j > -1; j--) {
if(Character.digit(str1.charAt(j), 10) != 0) {
System.out.println(count);
break;
} else {
count++;
}
}
}
}
Without using factorial
public class TrailingZero {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(trailingZeroes(9247));
}
public static int trailingZeroes(int a) {
int countTwo = 0;
int countFive = 0;
for (int i = a; i > 1; i--) {
int local = i;
while (local > 1) {
if (local % 2 != 0) {
break;
}
local = local / 2;
countTwo++;
}
while (local > 1) {
if (local % 5 != 0) {
break;
} else {
local = local / 5;
countFive++;
}
}
}
return Math.min(countTwo, countFive);
}}

how do i get even placed digits from a number in java

I want my program to get all the even digits from a number input. Then multiply those with digits with 2. If the result is a two digit number, add them. At the end i want it to give me the sum of all the even digits.
public class evenplaceadd {
public static void main(String[] args) {
System.out.println(sumOfevenPlace(5566));
}
public static int sumOfevenPlace(int number)
{
int maxDigitLength = 4;
int sum = 0;
for (int i = 0; i < maxDigitLength; i++)
{
if (i % 2 == 0)
{
int digita = number % 10;
int digitb =digita*2;
int digitc;
if(digita < 9)
{
sum = sum + digitb;
}
else if(digitb>9)
{
digitc =(digitb % 10)+ (digitb /10);
sum =sum + digitc;
}
}
else
{
number = number/10;
}
}
return sum;
}
}
Your code seems ok for the most part. There are some minor flaws in the code which I am sure you will be able to figure out after understanding the code provided below. I have changed it up a bit and made it easier to read. Please confirm it is working, and next time please provide the code when asking question. I know you are new to the community, and so am I. Its a learning experience for all of us. All the best in the future :)
public static void int sumOfEvenDigits(int num){
int sum = 0;
int lastDig = 0;
while(num/10 != 0)
{
lastDig = num % 10;
num = num / 10;
if(lastDig % 2 != 0)
{
continue;
}
if(lastDig > 10)
{
sum += lastDig / 10;
sum += lastDig % 10;
}
else
{
sum += lastDig;
}
}
return sum;
}

How to print a variable as defined in a method?

public class Program {
public static void main(String[] args) {
int lastFibo = 1; // ADDED TO check if last fib calculated is over 4000000
for (int i = 3; lastFibo <= 4000000; i = i + (i - 1)) {
lastFibo = fibo(i);
}
}
public static int fibo(int i) {
int total = 0;
if (i % 2 == 0) {
total += i;
return total;
}
return total;
}
}
The purpose of this code is to print the sum of even numbers in the fibonacci sequence who's values are less than 4 million. Using recursion the code returns a stack overflow error so it was recommended to iterate through the numbers. The difficulty encountered was knowing how to print the "total" variable. Scope articles are very basic and creating a static int total = 0 would return 0.
First, as pointed out by some comments: your for loop will not iterate the Fibonacci sequence. Second, the variable total exists only in the scope of your fibo method. So every time the method is called, total starts with the value 0.
Use the correct Fibonacci algorithm and add the return value of the fibo method up to calculate the sum:
public class Program {
public static void main(String[] args) {
int total = 0;
int previousValue = 0;
int currentValue = 1;
while (currentValue < 4_000_000) {
int nextPreviousValue = currentValue;
currentValue += previousValue;
previousValue = nextPreviousValue;
total += fibo(currentValue);
}
System.out.println(total);
}
public static int fibo(int i) {
if (i % 2 == 0) {
return i;
}
return 0;
}
}
4_000_000 is an integer literal you can use since Java 7 for the number 4000000. The purpose of the underscores is to make it better readable for humans. Programmatically there is no difference to using 4000000. For details see Primitive Data Types in The Java Tutorials.
Note: This first part of the question was related to a misunderstanding. I supposed that it was necessary to calculated up to fib(4000000).
You must use BigInteger otherwise you can't handle so big numbers. It is a number with many thousands of digits!
fib(4000000) results in a number with over 835k digits. It is not possible to handle it with int or long.
The class BigInteger (or the equivalent BigDecimal for decimal values) borns to handle such kind of problems.
Note: this is the answer to the question
Now that the question is more clear it is possible to give the correct answer.
public void printEvenFib() {
int i = 1;
int lastFib = 1;
int sum = 0;
while (lastFib <= 4000000) {
if (lastFib % 2 == 0) {
sum += lastFib;
}
i++;
lastFib = fib(i);
}
System.out.println(sum);
}
// Without recursion
public int fib(int n) {
if (n <= 2) {
return 1;
}
int fibo1 = 1;
int fibo2 = 1;
int fibo = 0;
for (int i = 3; i <= n; i++) {
fibo = fibo1 + fibo2;
fibo2 = fibo1;
fibo1 = fibo;
}
return fibo;
}
class Program2{
public static void main(String args[]){
int n1=0,n2=1,n3,total=0,i;
for(i=1;n3<4000000;++i){
n3=n1+n2;
if(n3%2==0)
total+=n3;
n1=n2;
n2=n3;
}
System.out.println("total is "+total);
}
}

first java program is not working

I'm new in Java, it's my first attempt to write a program:
I need to write a program that prints the sum of all positive integers smaller
than 1000, that are divided by either 3 or 5.
Here is my (poorly) attempt. after compiling it is just receiving numbers and showing them :
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
int num=1;
int count = 1;
while (count <=1000) {
if (count%3==0|count%5==0){
count = count+num;
count++;
}
}
System.out.println(count);
}
}
Given you used a while, I assume you don't know about for loops, so I'll avoid using it.
Your code should:
Your initial sum, before any number, is 0
Iterate (i.e. go through the values) the values from 1 to 1000
If the value is divisible by 3 or 5, add it to a sum.
Print the sum.
Point 1):
int sum = 0;
Point 2):
int value = 1;
while (value <= 1000) {
//do point 3
value++;
}
Point 3):
if ((value%3==0) || (value%5==0)) {
sum = sum + value;
}
Point 4):
System.out.println(sum);
Putting it all together:
int sum = 0;
int value = 1;
while (value <= 1000) {
if ((value%3==0) || (value%5==0)) {
sum = sum + value;
}
value++;
}
System.out.println(sum);
Your main error is in using count both for the sum and for the value check of the while condition. The misusage of the single pipe as or is also a mistake.
Hope this helps
public class Test {
public static void main(String[] args) {
int num=1;
int sum=0;
while (num <=1000) {
if (num%3==0||num%5==0){
sum = sum +num;
}
num++;
}
System.out.println(sum);
}
}
You have put your count++ inside if block. That means if the number is divisible by 3 or 5 then you are incrementing the count . Place it outside of your if block. I have re-write your code as follows -
import java.util.Scanner;
public class ex1 {
public static void main(String[] args) {
int sum = 0;
int count = 1;
while (count <=1000) {
if (count%3==0||count%5==0){
sum = sum + count;
}
count++;
}
System.out.println(sum);
}
}

Categories