Write a program to calculate and print the super factorial of a number using a for loop. The factorial of a number is the product of all integers up to and including that number, so the factorial of 4 (written as 4!) is 4*3*2*1= 24.
The super factorial is the product of all factorials up to and including that factorial.
4!!=4!*3!*2!*1!
I found "factorial" using the following code:
import java.util.Scanner;
public class superfactorial {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner (System.in);
// number whose factorial to be found
int number;
// prompting input
System.out.print("Enter number: ");
number = input.nextInt();
int factorial = factorial(number);
System.out.printf("the factorial of %d is %d", number , factorial);
}
// method that calculates the factorial
public static int factorial (int n){
int output = 1;
for (int i=1; i <= n; i++) {
output = output * i;
}
return output;
}
}
Consider 4! = 4x3x2x1, you can see that there are 4 numbers in the decomposition. in general there will be n numbers in the decomposition of n! (n(n-1)(n-2)....(n-(n-1)). So all you need to do to get the super factorial is take the factorial of each component in the decomposition.
pseudo-code looks something like this
sp = 0
for i = n to 1:
sp = sp * factorial(i)
end for
return sp
The most important line in your factorial method is this line:
output = output * i;
You multiply output by i where i is an integer that keeps increasing by one.
What's the difference between a superfactorial and a normal factorial? To evaluate a superfactorial, you multiply output not by i, but by the factorial of i, right?
So just do it! I have already explained the whole thing to you! Just create a new method called superfactorial, copy all the stuff from the factorial method and change this line:
output = output * i;
to this:
output = output * factorial(i);
Here is a recursive approach.
Basically, in factorial you multiply n * fact(n-1). Here, we do fact(n) * superFact(n-1) as we need product of all factorials.
int superfactorial(int n) {
if (n == 0 || n == 1) {
return factorial(n);
} else {
return factorial(n) * superfactorial(n-1);
}
}
int factorial(int n) {
if(n == 0 || n == 1) {
return n;
} else {
return n * factorial(n-1);
}
}
Related
This exercise required us to write a program for counting the number of candies the poor kids can get. The question is shown below:
You are requested to write a Java program to help these poor kids to answer this question. To generalize the solution, your program should be able to accept different values of n and m as input, where n = 10 and m = 2 in this question. To avoid infinite number of answers, you may assume that each candy has exactly one foil and it is not allowed to cut the foils.
And I follow the hints given to write the program using the provided formula and java recursion.
import java.util.Scanner;
public class MyFirstClass{
public static void main(String args[]){
Scanner a=new Scanner(System.in);
int n=0,m=0;
n = a.nextInt();
m = a.nextInt();
System.out.println("Candy " +n+" "+ m + " n="+ n+";m="+m+";No. of Candies="+total(n,m));
}
static int sum=0;
static int total(int n, int m)
{
int sum1=n;
sum1+=candy(n,m);
return sum1;
}
static int candy(int n,int m){
if((n+n%m)/m>1){
sum+=n/m+candy((n+(n%m))/m,m);
}
return sum;
}
}
However, when I set n=10 and m=2, the calculated total number of candies is less than the actual total number of candies by 1. What is the problem of my program? Thank you!
For your candy function:
static int candy(int n,int m){
if((n+n%m)/m>1){
sum+=n/m+candy((n+(n%m))/m,m);
}
return sum;
}
How does it even compile when sum is undefined?
In any case, the candy function needs to check the boundary condition of of when the first paramater is 0 or 1. And I'll assume negative numbers aren't valid input either.
int candy(int n, int m) {
if ((n <= 1) || (m == 0)) {
return 0;
}
return n/m + candy( ((n+n%m)/m), m);
}
And since it's "tail recursion", you can implement the entire thing with a while loop:
int candy(int n, int m) {
int result = 0;
while ((n > 1) && (m != 0))
{
result += n/m;
n = (n+n%m)/m;
}
return result;
}
This was part of my assignment and was asked to calculate factorial of 5 and 7.
I finished it as below:
import java.util.Scanner;
public class Factorial {
public static void main(String [] args)
{
System.out.println("Please enter a number: ");
Scanner input=new Scanner(System.in);
int number=input.nextInt();
int i,fact=1;
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of " + number + " is: " + fact);
}
}
It worked for 5 and 7 (resulting 120 and 5040).
But my professor came over and test it with 20 and 987654321, result returns -2102132736 and 0.
Why is that?
P.S. I thought for the case of 987654321, the result would crush the application or return error since it would be huge.
This code can solve your problem . It is taken from here
class BigFactorial
{
static void factorial(int n)
{
int res[] = new int[300];
// Initialize result
res[0] = 1;
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);
System.out.println("Factorial of given number is: ");
for (int i=res_size-1; i>=0; i--)
System.out.print(res[i]);
}
// 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
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 program
public static void main(String []args)
{
factorial(100);
}
}
Because 5040! is a very larger number (even long overflows). Use a BigInteger like
System.out.println("Please enter a number: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
BigInteger fact = BigInteger.ONE;
for (int i = 2; i <= number; i++) { // <-- x * 1 = x
fact = fact.multiply(BigInteger.valueOf(i));
}
System.out.println("Factorial of " + number + " is: " + fact);
This is because of the fact that the container that you have taken for storing and printing your result does not have the capacity to hold such big integer (I mean factorial of 20). So, you need a bigger container. As others already suggested, you can use BIGINTEGER.
I'm trying to find the average of integers elements in an array using recursion. I know how to do it using loops, but I have to do it by recursion for my assignment, so what I tried to do is to find the sum of elements using recursion and then divide the sum by the length of the array. I wrote this code but it gives me a wrong result:
public int findAvg(int a[], int n)
{
int sum,avg;
if(n==1)
{
sum=a[0];
return sum;
}
else
{
sum=a[n-1]+findAvg(a,n-1);
}
avg = sum/n;
return avg;}
The calling of findAvg method in main class:
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Recursive r = new Recursive ();
int integersArr [] = {1,2,3,4,5};
int max = r.findMax(integersArr,integersArr.length );
int avg = r.findAvg(integersArr, integersArr.length);
System.out.println("Maximum element = "+ max);
System.out.println("Average value of elements = "+ avg);
}
}
The console output:
Average value of elements = 1
First of all sum=a[n-1]+findAvg(a,n-1); is wrong, since if findAvg(a,n-1) returns the correct average for the first (n-1) elements, the sum should be a[n-1] + (n-1) * findAvg(a,n-1).
Second of all, you are losing precision when dividing integers in avg = sum/n; Consider using doubles.
First of all average of integers can be floating point. So make the return type of your function to float or double.
Now,
If you have set of n numbers with average of x and you want to add one more number to the set (say b). New average will be ((n * x) + b) / (n + 1). Use the same trick in your code.
public float findAvg(int a[], int n)
{
float sum,avg;
if(n==1)
{
sum=a[0];
}
else
{
// Calculate sum of n-1 numbers = (n-1) * (avg of n-1 numbers)
// and add nth number to it ( i.e. a[n-1])
sum= a[n-1]+ (n-1) * findAvg(a,n-1);
}
avg = sum/n;
return avg;
}
public double average(int y[], int i) {
double result;
result = (double)y[i] / (double)y.length;
if (i == 0)
return result;
else
return result + average(y, i-1);
}
public class main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Recursive r = new Recursive ();
int integersArr [] = {1,2,3,4,5};
int max = r.findMax(integersArr,integersArr.length );
int avg = r.findAvg(integersArr, integersArr.length);
System.out.println("Maximum element = "+ max);
System.out.println("Average value of elements = "+ avg);
}
}
I'm trying to compute the value of 7 factorial and display the answer, but when I tried to look up a way to do this I kept finding code that was written so that a number first had to be put in from the user and then it would factor whatever number the user put in. But I already know what number I need, obviously, so the code is going to be different and I'm having trouble figuring out how to do this.
I tried this at first
public class Ch4_Lab_7
{
public static void main(String[] args)
{
int factorial = 7;
while (factorial <= 7)
{
if (factorial > 0)
System.out.println(factorial*facto…
factorial--;
}
}
}
But all it does is display 7*7, then 6*6, then 5*5, and so on, and this isn't what I'm trying to do.
Does anyone know how to do it correctly?
import java.util.Scanner;
public class factorial {
public static void main (String[] args) {
Scanner input = new Scanner(System.in);
//Gives Prompt
System.out.print("Enter a number to find the factorial of it");
//Enter the times you want to run
int number = input.nextInt();
//Declares new int
int factor = 1;
//Runs loop and multiplies factor each time runned
for (int i=1; i<=number; i++) {
factor = factor*i;
}
//Prints out final number
System.out.println(factor);
}
}
Just keep multiplying it and until it reaches the number you inputted. Then print.
Input:5
Output:120
input:7
Output:5040
You need to have two variables, one for the factorial calculation and other for the purpose of counter. Try this, i have not tested it but should work:
public static void main(String[] args)
{
int input = 7;
int factorial = 1;
while (input > 0)
{
factorial = factorial * input
input--;
}
System.out.println("Factorial = " + factorial);
}
int a=7, fact=1, b=1;
do
{
fact=fact*b;//fact has the value 1 as constant and fact into b will be save in fact to multiply again.
System.out.print(fact);
b++;
}
while(a>=b); // a is greater and equals tob.
1st reason:
The methods you seen are probably recursive, which you seem to have edited.
2nd:
You are not storing, ANYWHERE the temporal results of factorial.
Try this
//number->n for n!
int number = 7;
//We'll store here the result of n!
int result = 1;
//we start from 7 and count backwards until 1
while (number > 0) {
//Multiply result and current number, and update result
result = number*result;
//Update the number, counting backwards here
number--;
}
//Print result in Screen
System.out.println(result);
Try this:
public static void main(String args[]) {
int i = 7;
int j = factorial(i); //Call the method
System.out.println(j); //Print result
}
public static int factorial(int i) { //Recursive method
if(i == 1)
return 1;
else
return i * factorial(i - 1);
}
This would print out the factorial of 7.
public class Factorial {
public static void main(String[] args) {
int result = factorial(5); //this is where we do 5!, to test.
System.out.println(result);
}
public static int factorial(int n) {
int x = 1;
int y = 1;
for (int i = 1; i <= n; i++) {
y = x * i;
x = y;
}
return y;
}
}
/*so, for 3! for example, we have:
i=1:
y = x * i, where x = 1, so that means:
y = 1*1 ; y= 1; x = y so x = 1. Then i increments =>
i = 2:
y = x * i. x is 1 and i is 2, so we have y = 2. Next step in code: x=y, means x = 2. Then i increments =>
i = 3:
y = x *i so we have y = 2*3. y=6. */
I'm supposed to use a recursive method to print out the digits of a number vertically.
For example, if I were to key in 13749, the output would be:
1
3
7
4
9
How should I approach this question?? It also states that I should use the if/else method to check for the base case.. I just started learning java and I'm not really good at it :(
import java.util.Scanner;
public class test2 {
public static void main (String [] args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int n = sc.nextInt();
System.out.println();
System.out.println(numbers(n));
}
public static int numbers(int n){
int sum;
if (n == 0) {
sum = 1;
} else {
System.out.println(n%10);
sum = numbers(n / 10) + (n % 10);
}
return sum;
}
}
Here is my code in C++
Just modify it for Java. You need to show the number after you call the function that way you show the last one first... as per the answer from s.ts
void recursive(int n) {
if (n < 10)
cout << n << endl;
else
{
recursive(n / 10);
cout << n % 10 << endl;
}
}
I was asked this question today in an interview!
public class Sandbox {
static void prints(int d) {
int rem = d % 10;
if (d == 0) {
return;
} else {
prints(d / 10);
}
System.out.println(rem);
}
public static void main(String[] args) {
prints(13749);
}
}
Output:
1
3
7
4
9
You asked how to approach this, so I'll give you a tip: it would be a lot easier to build up the stack and then start printing output. It also doesn't involve manipulating strings, which is a big plus in my book. The order of operations would be:
Check for base case and return if it is
Recursive call
Print
This way when you get to the base case, you'll start printing from the tail to the head of the calls:
recursive call 1
recursive call 2
recursive call 3
.... reached base case
print 3
print 2
print 1
This way you can simply print number % 10 and make the recursive call with number / 10, the base case would be when number is 0.
class PrintDigits {
public static void main(String[] args) {
String originalNumber, reverse = "";
// Creating an Scanner object
Scanner in = new Scanner(System.in);
System.out.println("Enter a number:");
// Reading an input
originalNumber = in.nextLine();
// Calculating a length
int length = originalNumber.length();
// Reverse a given number
for ( int i = length - 1 ; i >= 0 ; i-- )
reverse = reverse + originalNumber.charAt(i);
//System.out.println("Reverse number: "+reverse);
digits(Integer.parseInt(reverse));
}
/* digits of num */
public static void digits(int number) {
if (number == 0)
System.out.println("");
else {
int mode=10;
System.out.println(+number%mode);
digits(number/mode);
}
}
}
If number consists of more than one digit print ( n / 10 )
print ( n % 10 )
If you want them printed in the other order
print ( n % 10 )
If number consists of more than one digit print ( n / 10 )
try this
public class Digits {
public static void main(String[] args) {
printDigits(13749);
}
private static void printDigits(Integer number) {
int[] m = new int[number.toString().toCharArray().length];
digits(number, 0, m, 0);
for (int i= m.length - 1; i>=0; i--) {
System.out.println(m[i]);
}
}
public static int digits(int number, int reversenumber, int[] m, int i) {
if (number <= 0) {
return reversenumber;
}
m[i] = (number % 10);
reversenumber = reversenumber * 10 + (number % 10);
return digits(number/10, reversenumber, m, ++i);
}
}
Python example
def printNoVertically(number):
if number < 9:
print(number)
return
else:
printNoVertically(number/10)
print(number % 10)