long factorial (int x) {
if (x == 0)
return 1; //base case
else
return x * factorial (x – 1); //recursive case
}
I have this recursive method for computing x!
I try to write mine for it in NetBeans because I want to see the output for this method but I don't know how to start writing the mine...how can I invoke it in the main to print it?
I hope you can understand my problem
Use public static void main(String[] args) to call the factorial function inside it.
The factorial function must be static because the static function can only reference static functions.
// "static void main" must be defined in a public class.
public class Main {
public static long factorial(int x) {
if (x == 0)
return 1; //base case
else
return x * factorial(x-1); //recursive case
}
public static void main(String[] args) {
System.out.println(factorial(5));
}
}
class calc_factorial {
public static void main(String args [ ]) {
calc_factorial obj = new calc_factorial( );
int num = 5;
long answer = obj.factorial(num);
System.out.println("Factorial of " + num + " is " +
answer);
}
long factorial(int x){
if(x == 1)
return 1
else
return factorial(x-1) * x;
}
}
Related
I want to reverse an int but it doesn't work. For example, 123 should return 321, but the printed number is 356.
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return 0;
} else {
i = i*10 + a%10;
System.out.println(i);
return i += reverse2(a/10, i);
}
}
}
Your code should look like this:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123, 0));
}
static int reverse2(int a, int i) {
if(a == 0) {
return i;
} else {
i = i*10 + a%10;
System.out.println(i);
return reverse2(a/10, i);
}
}
}
You should return i when a is 0.
You shouldn't add i when you call the reverse2 function because you're adding i twice.
You are greatly complicating your recursive function for printing an integer in reverse. For one, there is no good reason for reverse2 to have two integer arguments, as you can achieve your desired results with a single argument. The trick is to access the rightmost digit with the % 10 operation then shift that digit off the number with the / 10 operation. Consider these revisions:
public class x {
public static void main(String[] args) {
System.out.println(reverse2(123));
}
static String reverse2(int number) {
if(number == 0) {
return "";
} else {
return number % 10 + reverse2(number / 10);
}
}
}
You can do it like this. You only need to pass the value you are reversing. The math computation computes 10 to the power of the number of digits in the argument.
public static int reverse(int v) {
int reversed = 0;
if (v > 0) {
int d = (int)Math.pow(10,(int)(Math.log10(v)));
reversed = reverse(v%d) * 10 + v/d;
}
return reversed;
}
Of course, if you can pass a second argument as a scratch pad, then it can be done like so. As you tear down the original value you build up the returned value.
public static int reverse(int v, int reversed) {
if (v > 0) {
return reverse(v / 10, reversed * 10 + v % 10);
}
return reversed;
}
I have the following exercise that I'm trying to solve:
Write a class Summing with a method public static void sumit(). The
method computes the sum of all numbers between 1 an 200 which are
divisble by 7 and prints the result in the form
"The sum is NUMBER"
where "NUMBER" is the sum.
Here is what I've written so far:
public class Summing {
public static void main(String[] args) {
public static void sumit() {
for(int i = 0; i <= 200; i += 7) {
System.out.print("The sum is " + i);
}
}
}
}
I'm not sure how I correctly call on the sumit() method here. Can anybody point out to me how I properly create the method sumit()?
The execution of a program always starts from the main() method, so you need to call the sumit() method inside the main() method, like below:
public static void main(String[] args) {
sumit();
}
public static void sumit() {
for(int i = 0; i <= 200; i += 7) {
System.out.print("The sum is " + i);
}
}
But still there is issue with your code, which won't give you the sum of all numbers that are divisible by 7 between 0 and 200, so have a local variable which will add all numbers that are divisible by 7 in for loop
public static void sumit() {
int sum=0;
for(int i = 0; i <= 200; i += 7) {
sum+=i; //sum = sum+i;
System.out.println("The sum is " + sum);
}
}
You cannot put a method inside another method so rather do this:
-Write your method outside the main method
public class Summing
{
public static void main(String[] args)
{
sumit();
}
public static void sumit() {
for(int i = 0; i <= 200; i += 7) {
System.out.print("The sum is " + i);
}
}
}
If I understand the requirement correctly, this guy should do it.
Give it a try ;]
public class Summing {
public static void main(String[] args) {
sumit();
}
public static void sumit() {
int sum = 0;
for(int i = 0; i <= 200; i++) {
if (i % 7 == 0) {
sum = sum + i;
}
}
System.out.print("The sum is " + sum);
}
}
public class collatzpow {
public static int collatz(int n) {
StdOut.print( n + " ");
if (n == 1) return 0;
if (n% 2 == 0) return collatz(n/2);
else return collatz(3*n + 1);
}
public static void main(String[] args) {
int n= Integer.parseInt(args[0]);
StdOut.println(collatz(7));
}
}
I want to set up a global variable to count the number of time the program calls the recursion. I know with the number 7 it calls it 17 times.
I've been told it is very easy, but I'm struggling a bit with it.
Just declare a static int variable in the class scope and increment each time the method is called.
public class collatzpow {
public static int count = 0;
public static PrintStream StdOut = System.out;
public static int collatz(int n) {
++count;
StdOut.print(n + " ");
if (n == 1) return 0;
if (n % 2 == 0) return collatz(n / 2);
else return collatz(3 * n + 1);
}
public static void main(String[] args) {
int n = Integer.parseInt(args[0]);
StdOut.println(collatz(7));
System.out.println(count);
}
}
Hello I have written the following code to return the factorial of n when the the value is 10 but i cant get my program to work. I have never used Java before and I am a beginner.
public static int Factorial(n)
{
if (n == 0) {
return 1;
} else {
return( n * Factorial(n-1) );
}
}
public static int main(args) {
System.out.println(Factorial(10));
}
You lack a few type definitions and the required main method. Your class should look like this to work:
public class Main {
public static int Factorial(int n) {
if (n == 0) {
return 1;
} else {
return(n * Factorial(n-1));
}
}
public static void main(String args[]) {
System.out.println(Factorial(10));
}
}
You could also try this:
int factorial(int n)
{
return (n>=1 ? n * factorial(n-1) : 1);
}
I am practicing recursion and I can't see why this method does not seem to work.
Any ideas?
public void fact()
{
fact(5);
}
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
}
Thanks
Your code seems to work but you are not doing anything with the returned value, put method call fact or fact(5) inside of a System.out.println and see what you get.
The recursion part is fine; you're just not using its return value, which gets discarded. Here's a complete Java application of your factorial code, slightly jazzed-up for educational purposes:
public class Factorial {
public static String fact(int n) {
if(n == 1){
return "1";
}
return n + " * " + (fact(n-1)); // what happens if you switch the order?
}
public static void main(String[] args) {
System.out.println(fact(5));
// prints "5 * 4 * 3 * 2 * 1"
}
}
A simplified version of your code:
public int fact(int n)
{
if(n == 1){
return 1;
}
return n * (fact(n-1));
}
could be just:
public int fact(int n)
{
return n == 1 ? 1 : n * fact(n - 1);
}
but your code is not wrong, this is just another style (if you are not used to ternary operator keep the way it is). I prefer use the ternary operator in these cases (observe that the code is side effect free).
Works fine. You're not assigning it to anything. Here's a test that'll prove it works.
#Test
public void testYourFactorialMethod() {
assertEquals(120, fact(5));
}
public class Recursive {
public static void main(String[] argss) {
System.out.print(fac(3));
}
public static int fac(int n) {
int value = 0;
if (n == 0) {
value = 1;
} else {
value = n * fac(n - 1);
}
return value;
}
}
// out put 6
Try something like this:
(Or maybe try this directly)
public class factorial {
private static int factorial( int n ){
if (n > 1) {
return n * (factorial(n-1));
} else {
return 1;
}
}
public static void main(String[] args) {
System.out.println(factorial(100));
}
}
static int factorial(int x) {
int result;
if (x == 1) {
return 1;
}
// Call the same method with argument x-1
result = factorial(x – 1) * x;
return result;
}
For complete example check this
http://answersz.com/factorial-program-in-java-using-recursion/
It is totaly wrong to write Fibonacci with recursive methods!!
It is an old famous example for how a good/bad Algorythm affect any project
if you write Fibonatcci recursive, for calculating 120 you need 36 year toget the result!!!!!!
public static int Fibonacci(int x)
{ // bad fibonacci recursive code
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
in dot net 4.0 there is a new type name BigInteger and you can use it to make a better function
using System;
using System.Collections.Generic;
using System.Numerics; //needs a ref. to this assembly
namespace Fibonaci
{
public class CFibonacci
{
public static int Fibonacci(int x)
{
if (x <= 1)
return 1;
return Fibonacci(x - 1) + Fibonacci(x - 2);
}
public static IEnumerable<BigInteger> BigFib(Int64 toNumber)
{
BigInteger previous = 0;
BigInteger current = 1;
for (Int64 y = 1; y <= toNumber; y++)
{
var auxiliar = current;
current += previous;
previous = auxiliar;
yield return current;
}
}
}
}
and you can use it like
using System;
using System.Linq;
namespace Fibonaci
{
class Program
{
static void Main()
{
foreach (var i in CFibonacci.BigFib(10))
{
Console.WriteLine("{0}", i);
}
var num = 12000;
var fib = CFibonacci.BigFib(num).Last();
Console.WriteLine("fib({0})={1}", num, fib);
Console.WriteLine("Press a key...");
Console.ReadKey();
}
}
}
and in this case you can calculate 12000 less than a second. so
Using Recursive methos is not always a good idea
Above code imported from Vahid Nasiri blog whiche wrote in Persian