How do I make a function return the sum of all digits until it becomes a 1 digit number, using recursion? I was able to make a function that gets the sum of all digits, but cant seem to find a way to recursively sum the digits of the sum itself:
class sum_of_digits
{
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
return (n % 10 + sum_of_digit(n / 10));
}
public static void main(String args[])
{
int num = 12345;
int result = sum_of_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
}
This code prints the sum of '12345', which is 15. But I need to change it so it prints the sum of 1 + 5, which is 6.
do you think it is possible to make it work without an additional
method?
Why can't we just let the recursion do the work for us and simply say:
static int sum_of_digit(int n)
{
if (n < 10)
return n;
return sum_of_digit(n % 10 + sum_of_digit(n / 10));
}
Things will become a lot easier if you define an additional recursive "layer" in conjunction with sum_of_digit. This new function can call sum_of_digit until it has a single digit as a result. Here is what I mean:
static int sum_to_one_digit(int n) {
if(n/10 == 0) return n;
return sum_to_one_digit(sum_of_digit(n));
}
The code from main will be:
public static void main(String args[])
{
int num = 12345;
int result = sum_to_one_digit(num);
System.out.println("Sum of digits in " +
num + " is " + result);
}
You could add a clause at the end to check whether the sum is smaller than 10, if it isn't then recursively call it again with the newly calculated sum, ie.
static int sum_of_digit(int n)
{
if (n == 0)
return 0;
int temp = (n % 10 + sum_of_digit(n / 10));
if (temp < 10)
return temp;
return sum_of_digit(temp);
}
There are several ways to do it, one would be like this if global variables are allowed :
public class Sum_of_digits{
static int sum = 0;
public static void main(String args[]){
int n = 12345;
System.out.println(sum_of_digit(n));
sum = 0;
}
static int sum_of_digit(int n){
if(n==0){
if(sum/10 == 0){
return sum;
}else{
n=sum;
sum=0;
}
}
sum = sum+(n%10);
n=n/10;
return sum_of_digit(n);
}
}
and if Global variable are not allowed then passing sum as a parameter will help :
public class Sum_of_digits{
public static void main(String args[]){
int n = 12345;
int sum = 0;
System.out.println(sum_of_digit(n,sum));
}
static int sum_of_digit(int n,int sum){
if(n==0){
if(sum/10 == 0){
return sum;
}else{
n=sum;
sum=0;
}
}
sum = sum+(n%10);
n=n/10;
return sum_of_digit(n,sum);
}
}
Here we are just shifting the focus from n to sum to evaluate the condition when the loop/recursion will terminate.
Related
I'm trying to create a recursive function that returns the average of the digits in a number. For example the average of the number 123 is 2.
I know how to write a function that sums the digits.
public static int sum (int n) {
if (n<10)
return n;
return n%10 + sum(n/10);
}
I also know how to count the digits
public static int numCount(int n) {
if (n<10)
return 1;
return 1 + numCount(n/10);
}
However I can't figure out how to calculate the average without using pre existing functions.
You can recursively iterate the array while keeping both accumulative sum and an index that shows which items were already iterated:
public class MyClass {
public static void main(String args[]) {
int[] arr = {1,2,3};
System.out.println(avg(arr)); // 2.0
}
private static double avg(int[] arr) {
return avg(arr, 0, 0);
}
private static double avg(int[] arr, int index, int sum) {
if (index == arr.length) {
return (double) sum / index;
}
return avg(arr, index + 1, sum + arr[index]);
}
}
Demo
Try this:
int recursive(int num, int startingSize) {
if(num < 10){
return num;
}
num = num % 10 + recursive(num/10, startingSize++);
return num/startingSize;
}
and for example : recursive(123, 1)
count=0;
public static int sum (int n) {
count++;
if (n<10)
return n;
return n%10 + sum(n/10);
}
double average = (double)sum(123)/count;
System.out.println("average:"+ average);
I mean if we are just talking numbers we don't even need recursive functions here
String s = Double(10.45).toString();
Int size = s.length();
int count = 0;
Int sum = 0;
for (int i = 0; i < size; I++ ) {
try {
sum += Integer.valueOf(s[i]);
++count;
} catch (Exception e) {}
}
return sum / count;
That should give you an. Average regardless of number, whole or real.
I am trying to write a recursive function that when I call with number 5 for example then the function will calculate the sum of all digits of five.
1 + 2 + 3 + 4 + 5 = 15
The current code always returns 0, how can the amount each time the n?
public class t {
public static void main(String[] args) {
System.out.println(num(5));
}
public static int num(int n) {
int sum = 0;
sum += n;
if (n == 0)
return sum;
return num(n - 1);
}
}
thank you.
Instead of setting the sum to 0 you can -
Do this:
public int sumUp(int n){
if (n==1)
return 1;
else
return sumUp(n-1)+n;
}
The problem is you set the sum always 0.
public static void main(String[] args) {
System.out.println(num(5, 0));
}
public static int num(int n, int sum) {
if (n == 0) {
return sum;
}
sum += n;
return num(n - 1, sum);
}
public static int withRecursion(List<Integer> list) {
int size = list.size();
int a=0;
if(list.isEmpty() == true) {
return 0;
}else {
a = a + list.get(0) + withRecursion(list.subList(1, size));
return a;
}
}
This is my code so far but when I run it and enter a value for n the program ends with "Sum of numbers is: " and that's all. Doesn't change no matter what value I enter, can you help me figure out what I'm doing wrong?
import java.util.Scanner;
class addNum
{
//A method for Adding
public static int addNum (int arr[], int n)
{
int x = 0;
if (n > arr.length)
{
return 0;
}
else if (n == 1)
{
return 1;
}
else
{
x = arr[n-1] + addNum(arr, n);
return n;
}
}
public static void main(String args[])
{
int n = 0;
int arr[] = {1,2,3,4,5,6,7};
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.print("Sum of numbers is:");
addNum(arr, n);
System.out.println();
}
}
try changing it to
System.out.println(addNum(arr, n));
so something is actually returned and printed
and there is a bug
x = arr[n-1] + addNum(arr, n);
return x; // not n
addNum(arr, n);
This is just a function call addNum(param1, param2).
It will only be returning value, not printing out value.
Thus, you have to print that value out in order to be able to see it.
System.out.println(addNum(arr, n));
As mentioned by Siren P. will work
Try this:
public static int addNum (int arr[], int n)
{
int x = 0;
if (n > arr.length)
{
return 0;
}
else if (n == 1)
{
//When n == 1, you want to return the first element of your array and not 1
return arr[0];
}
else
{
//As you go deeper into recursion, you break your problem into a smaller problem.
//Therefore, when calling addNum again, you pass n-1 and not n, as now you want to add remaining n-1 numbers
x = arr[n-1] + addNum(arr, n-1);
// you want to return your sum x and not n
return x;
}
}
public static void main(String args[])
{
int n = 0;
int arr[] = {1,2,3,4,5,6,7};
System.out.println("Input your number and press enter: ");
Scanner in = new Scanner(System.in);
n = in.nextInt();
System.out.print("Sum of numbers is:");
//Your addNum method returns an int, so you want to save it in a variable and then print it
int x = addNum(arr, n);
System.out.println(x);
}
I need to implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.
This is what I have so far:
public class PrintDigits {
public static void main(String[] args) {
System.out.println("Reverse of no. is " + reversDigits(91));
}
/* Recursive function to reverse digits of num */
public static int reversDigits(int number) {
if (number == 0)
return number;
else {
return number % 10;
}
}
}
I feel like there is only one line of code that I am missing, but not sure what I need to do to fix it.
public static void main(String[] args) {
reverseDigits(98198187);
}
/* Recursive function to reverse digits of num */
public static void reverseDigits(long number) {
if (number < 10) {
System.out.println(number);
return;
}
else {
System.out.println(number % 10);
reverseDigits(number/10);
}
}
This doesn't exactly answer the question, but it actually computes the entire reversed number instead of printing the digits as they are calculated. The result is an int with the digits in reversed order. Much more powerful than printing out the string version of the numbers one by one:
public class Reverse {
public static void main(String[] args) {
// input int parameter
int param = Integer.parseInt(args[0]);
System.out.println(reverse(param));
}
public static int reverse(int input) {
return reverse(input, 0);
}
private static int reverse(int original, int reversed) {
// get the rightmost original digit and remove it
int rightmost = original % 10;
original -= rightmost;
original /= 10;
// add rightmost original digit to left of reversed
reversed += rightmost * Math.pow(10, numDigits(original));
return (original == 0)
? reversed
: reverse(original, reversed);
}
public static int numDigits(int number) {
number = Math.abs(number);
if (number >= 10) {
return 1 + numDigits(number /= 10);
} else if (number > 0) {
return 1;
} else {
return 0;
}
}
}
public static void reversDigits(long number) {
System.out.println(number % 10);
if (number >= 10) {
reversDigits(number / 10);
}
}
This is shortest/simplest version so far;)
public static int reversDigits(int num) {
if(num < 1) {
return 0;
}
int temp = num % 10;
num = (num - temp)/10;
System.out.println(temp);
return reversDigits(num);
}
This will print the digits one at a time in reverse order. You don't need to do System.out in your main method.
I found I had to pick off the highest digit (on the left) and work towards the rightmost digit. I couldn't get a recursive one to work going from right to left.
public static int reverseItRecursive(int number)
{
if (number == 0)
return 0;
int n = number;
int pow = 1;
while (n >= 10)
{
n = n / 10;
pow = pow * 10;
}
return (n + reverseItRecursive(number - n*pow)*10);
}
This should work
int rev = 0;
int reverse(int num)
{
if (num < 10) {
rev = rev*10 + num;
}
else {
rev = rev*10 + (num % 10);
num = reverse(num / 10);
}
return rev;
}
//Try out this, recursion with singe variable using Math class.
public static void main(String[] args) {
// Let the number be 139
int n=139;
System.out.println("reverse is "+rev(n));
}
static int rev(int n){
if (n==0)return 0;
else {
return n%10*(int) Math.pow(10,(double) (int)Math.log10(n))+rev(n/10);
}
}
This method reverse the integer and returns the result without using any string functions, Math, or by just printing
public class ReverseNumber {
public static void main (String[] args) {
ReverseNumber rNumber = new ReverseNumber();
System.out.println(rNumber.reverseRecursive(1234,0)); // pass zero to initialize the reverse number
}
public int reverseRecursive(int n, int reverse) {// n - the number to reverse
// System.out.println(n);
if (n != 0){
reverse = reverse * 10;
reverse = reverse + n %10;
n = n/10;
} else {
return reverse;
}
return reverseRecursive(n,reverse);
}}
public void reverse(int num){
System.out.print(num %10);
if(num / 10 == 0){
return;
}
reverse(num /10);
return;
}
This is very shortest/simplest way in two lines code:
public static int reverseNumber(int n)
{
System.out.println(n % 10);
return (n/10 > 0) ? reverseNumber(n/10) : n;
}
I came looking for a more elegant version than mine, but perhaps this just requires a bit of a messy algorithm. Mine also returns the actual integer value which I agree is much more useful than only printing the string:
Mine:
public static int reverse(int n){
if(n<10)return n;
return n%10*(int)Math.pow(10,(int)Math.log10((double)n)) + reverse(n/10);
}
so this returns the last digit, multiplied by 10^current power + (recursive call)
Here you go :
static String reverseDigits(int n)
{
String N = "";
if ( n== 0)
return N;
else
{
N += n%10;
return N + reverseDigits(n/= 10);
}
}
This is of course returned as String.
If you want it as int all you have to do is parse it using Integer.parseInt()
//Reverse a number using recursion by bibhu.rank
public class Rev_num {
public static int revnum(int x){
int temp1=x,temp2=1;
if(x<10){
return x;
}
while(temp1>=10){
temp2*=10;
temp1/=10;
}
if(((x%temp2) < (temp2/10))&& x%temp2!=0){
int c=temp2;
while(c> x%temp2){
c/=10;
}
c=temp2/c;
temp2=x%temp2;
return((temp1)+(c*revnum(temp2)));
}
temp2=x%temp2;
return (temp1+(10*revnum(temp2)));
}
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println("Enter a number");
Scanner y=new Scanner(System.in);
System.out.println(revnum(y.nextInt()));
y.close();
}
}
public class reverseIntRec{
public static void main(String args[]) {
System.out.println(reverse(91));
}
public static int reverse(int x) {
String strX = String.valueOf(x);
if (Math.abs(x) < 10)
return x;
else
return x % 10 * ((int) Math.pow(10, strX.length()-1)) + reverse(x/10);
}
}
Here is my answer return as integer. I converted x into string to see how many 0s you should multiply with.
For example: reverse(91) returns 1 * 10 + reverse (9), and that returns 10 + 9 = 19.
Relatively simple since you need to print one digit per line. You also state that you print its digits, which implies that leading zeros are still going to be displayed. Our test case
123000 prints :
0
0
0
3
2
1
here is the code, no while, no string, and no math library :
private void printIntegerDigitsReversed(int i) {
if (i / 10== 0 ){
System.out.println(i);
}
else{
printIntegerDigitsReversed(i%10);
printIntegerDigitsReversed(i/10);
}
}
I tried to find the factorial of a large number e.g. 8785856 in a typical way using for-loop and double data type.
But it is displaying infinity as the result, may be because it is exceeding its limit.
So please guide me the way to find the factorial of a very large number.
My code:
class abc
{
public static void main (String[]args)
{
double fact=1;
for(int i=1;i<=8785856;i++)
{
fact=fact*i;
}
System.out.println(fact);
}
}
Output:-
Infinity
I am new to Java but have learned some concepts of IO-handling and all.
public static void main(String[] args) {
BigInteger fact = BigInteger.valueOf(1);
for (int i = 1; i <= 8785856; i++)
fact = fact.multiply(BigInteger.valueOf(i));
System.out.println(fact);
}
You might want to reconsider calculating this huge value. Wolfram Alpha's Approximation suggests it will most certainly not fit in your main memory to be displayed.
This code should work fine :-
public class BigMath {
public static String factorial(int n) {
return factorial(n, 300);
}
private static String factorial(int n, int maxSize) {
int res[] = new int[maxSize];
res[0] = 1; // Initialize result
int res_size = 1;
// Apply simple factorial formula n! = 1 * 2 * 3 * 4... * n
for (int x = 2; x <= n; x++) {
res_size = multiply(x, res, res_size);
}
StringBuffer buff = new StringBuffer();
for (int i = res_size - 1; i >= 0; i--) {
buff.append(res[i]);
}
return buff.toString();
}
/**
* This function multiplies x with the number represented by res[]. res_size
* is size of res[] or number of digits in the number represented by res[].
* This function uses simple school mathematics for multiplication.
*
* This function may value of res_size and returns the new value of res_size.
*/
private static int multiply(int x, int res[], int res_size) {
int carry = 0; // Initialize carry.
// One by one multiply n with individual digits of res[].
for (int i = 0; i < res_size; i++) {
int prod = res[i] * x + carry;
res[i] = prod % 10; // Store last digit of 'prod' in res[]
carry = prod / 10; // Put rest in carry
}
// Put carry in res and increase result size.
while (carry != 0) {
res[res_size] = carry % 10;
carry = carry / 10;
res_size++;
}
return res_size;
}
/** Driver method. */
public static void main(String[] args) {
int n = 100;
System.out.printf("Factorial %d = %s%n", n, factorial(n));
}
}
Hint: Use the BigInteger class, and be prepared to give the JVM a lot of memory. The value of 8785856! is a really big number.
Use the class BigInteger. ( I am not sure if that will even work for such huge integers )
Infinity is a special reserved value in the Double class used when you have exceed the maximum number the a double can hold.
If you want your code to work, use the BigDecimal class, but given the input number, don't expect your program to finish execution any time soon.
The above solutions for your problem (8785856!) using BigInteger would take literally hours of CPU time if not days. Do you need the exact result or would an approximation suffice?
There is a mathematical approach called "Sterling's Approximation
" which can be computed simply and fast, and the following is Gosper's improvement:
import java.util.*;
import java.math.*;
class main
{
public static void main(String args[])
{
Scanner sc= new Scanner(System.in);
int i;
int n=sc.nextInt();
BigInteger fact = BigInteger.valueOf(1);
for ( i = 1; i <= n; i++)
{
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println(fact);
}
}
Try this:
import java.math.BigInteger;
public class LargeFactorial
{
public static void main(String[] args)
{
int n = 50;
}
public static BigInteger factorial(int n)
{
BigInteger result = BigInteger.ONE;
for (int i = 1; i <= n; i++)
result = result.multiply(new BigInteger(i + ""));
return result;
}
}
Scanner r = new Scanner(System.in);
System.out.print("Input Number : ");
int num = r.nextInt();
int ans = 1;
if (num <= 0) {
ans = 0;
}
while (num > 0) {
System.out.println(num + " x ");
ans *= num--;
}
System.out.println("\b\b=" + ans);
public static void main (String[] args) throws java.lang.Exception
{
BigInteger fact= BigInteger.ONE;
int factorialNo = 8785856 ;
for (int i = 2; i <= factorialNo; i++) {
fact = fact.multiply(new BigInteger(String.valueOf(i)));
}
System.out.println("Factorial of the given number is = " + fact);
}
import java.util.Scanner;
public class factorial {
public static void main(String[] args) {
System.out.println("Enter the number : ");
Scanner s=new Scanner(System.in);
int n=s.nextInt();
factorial f=new factorial();
int result=f.fact(n);
System.out.println("factorial of "+n+" is "+result);
}
int fact(int a)
{
if(a==1)
return 1;
else
return a*fact(a-1);
}
}