I have updated my code with a recursive factorial method, but still need help that isn’t condescending. Also, can someone tell me how to format my hyperlinks to shorter text? I know my code isn’t the greatest, and I’m really trying.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static int factorial (int n){
if (n == 0){
return 1;
}
else{
return (n * factorial (n - 1));
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner (System.in);
int testCase = in.nextInt();
int [] array = new int [testCase];
for (int i = 0; i < array.length; i++){
int temp, n, sum =0;
temp = array[i];
}
}
}
I have the following, but now I’m unable to find a value for n. I don’t understand why?
class Codechef
{
public static int factorial (int n){
if (n == 0){
return 1;
}
else{
return (n * factorial (n - 1));
}
}
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner (System.in);
int testCase = in.nextInt();
int [] array = new int [testCase];
for (int i = 0; i < array.length; i++){
int temp, n, sum =0;
temp = in.nextInt();
while (temp >0){
n = temp % 10;
sum += n;
temp /= 10;
}
factorial(n);
}
}
}
I was taking the sum to keep up with how many digits are in the array. I want to divide my temp by 10 so that I can get it back down to 0, but that isn’t working. I do appreciate you taking the time to look over and give constructive criticism.
Listen my bro . You don’t have to do all this .
You made factorial function.
You made array for storing testcases.
for (int i = 0; i < array.length; i++){
int temp, n, sum =0;
temp = in.nextInt();
array[i]=temp; }
.
Then for every number calculate its factorial .
for( int i=0;i<array.length;i++)
array[i]=factorial(array[i]);
print the array .
for(int num:array)
System.out.println(num);
The problem I am having is trying to figure out how to add each individual digit into an array. I think that is why they suggested hard coding the size of the array to two-hundred.