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;
}
}
Related
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.
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 print 122333221 using recursion if n is 3.But i am not able to solve it.We have given the number we have to print the series using recursion.For example if n = 3 then it should print 122333221.
public static void print(int n){
if(n < 1 ){
return;
}
print(n-1);
for(int i = 1; i <= n; i++){
System.out.print(n);
}
}
public static void main(String[] args) {
print(3);
}
You have to use the normal technique of keeping track of your state through parameters by defining a public method which uses a private method with extra parameters.
// Repeats n n times.
private static void repeat(int n) {
for (int i = 0; i < n; i++) {
System.out.print(n);
}
}
private static void print(int n, int v) {
if (n == v) {
// Just once for the deepest level.
repeat(n);
} else {
// Wrap the inner print ...
repeat(n);
// Recurse with the next higher value.
print(n + 1, v);
// ... end the wrap.
repeat(n);
}
}
public static void print(int n) {
System.out.print(n+": ");
print(1, n);
System.out.println();
}
public void test(String[] args) {
for (int i = 1; i <= 9 ; i++) {
print(i);
}
}
a possible solution will be n is the number of the different digits you have , while you need to print each digit times its value, so if n = 1
result =1
n =2 result 1221
n = 3, result 122333221
n = 4, result 1223334444333221
The implemenation is not hard , the base case is the number = n and its printed n times and you always print recursivly unless you reached n, the first call is always
solve(n, 1,1);
The implementation:
public void solve(int n, int numberOfPrints, int num) {
if(numberOfPrints == 0 && n ==num )
return ;
if(numberOfPrints == 0 )
solve(n, num+1,num+1);
System.out.print(num);
solve(n, numberOfPrints-1, num);
if(num == n)
return;
System.out.print(num);
}
public static void PrintSeries(int seriesNum, int currentNum, bool movingForward)
{
if(movingForward && currentNum < seriesNum)
{
PrintNum(currentNum);
PrintSeries(seriesNum, currentNum + 1, true);
}
else if(movingForward && currentNum == seriesNum)
{
PrintNum(currentNum);
PrintSeries(seriesNum, currentNum - 1, false);
}
else
{
if(currentNum > 0)
{
PrintNum(currentNum);
}
if(currentNum - 1 > 0)
{
PrintSeries(seriesNum, currentNum - 1, false);
}
}
}
public static void PrintNum(int num)
{
for(int x = 0; x < num; x++)
{
System.out.print(num);
}
}
Can't find out how to go further when working with two unknown integers in parameters. Have several tasks regarding this.
returning the sum between two unknown integers, the two unknown numbers have to be included in the calculation as well
returning the even numbers between the two unknown
returning the odd numbers between the two unknown
returning the prime numbers between the two unknown
I know this probably is very easy, but still can't find out how to get started.
public int method(int a, int b){
sum = 0;
??for() {
}??
public static void main(String[] args) {
System.out.println("sum: " + sum(10, 12));
System.out.println("evens: " + evens(10, 20));
System.out.println("odds: " + odds(10, 20));
System.out.println("primes: " + primes(0, 100));
}
public static int sum(int from, int to) {
int sum = 0;
for (int i = from; i <= to; i++) {
sum += i;
}
return sum;
}
public static List<Integer> evens(int from, int to) {
List<Integer> evens = new ArrayList<>();
if (from % 2 != 0) {
from++;
}
for (int i = from; i <= to; i += 2) {
evens.add(i);
}
return evens;
}
public static List<Integer> odds(int from, int to) {
List<Integer> odds = new ArrayList<>();
if (from % 2 == 0) {
from++;
}
for (int i = from; i <= to; i += 2) {
odds.add(i);
}
return odds;
}
public static List<Integer> primes(int from, int to) {
List<Integer> primes = new ArrayList<>();
boolean prime = false;
for (int i = from; i <= to; i++) {
if (isPrime(i)) {
primes.add(i);
}
}
return primes;
}
public static boolean isPrime(int n) {
for(int i = 2; 2 * i < n; i++) {
if(n % i == 0) {
return false;
}
}
return true;
}
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);
}
}