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;
}
Related
The program works fine for small numbers but as soon as i take a big number like this it doesn't work
here is my code
public class Main {
public static void main(String[] args) {
long no=600851475143L,i;
int result=0;
for(i=(no/2);i>=2;i--){
if(no%i==0){
if(checkPrime(i)){
System.out.println("Longest Prime Factor is: " + i);
break;
}
}
}
}
private static boolean checkPrime(long i){
for(long j=2L;j<=(int)Math.sqrt(i);j++){
if(i%j==0)
return false;
}
return true;
}
}
to assign long variable value we does not require write L at last on value Remove L.
It will take time to display the answer. Just try with small number(1000000 ) almost 10 to 15 min for above code.
Try this
public class Main {
public static void main(String[] args) {
//long no=600851475143L,i;
System.out.println(largestPrimeFactor(600851475143L));
}
public static int largestPrimeFactor(long number) {
int i;
for (i = 2; i <= number; i++) {
if (number % i == 0) {
number /= i;
i--;
}
}
return i;
}
}
[1]https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
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);
}
}
The input for this method is "9876548"
It returns
8
4
5
6
7
8
9
9876548
I don't want the "9876548" at the end.
(Stack over flow format wont all
Implement a recursive method printDigits that takes an integer num as a parameter and prints its digits in reverse order, one digit per line.
public class PrintDigits{
public static void main (String [] args)
{System.out.print(reversDigits(9876548));}
public static int reversDigits(int number) {
int result;
if (number < 10) {
System.out.println(number);
result = number;
}
else{
System.out.println(number % 10);
reversDigits(number/10);
result = number;
}
return result;
}
}
Thank you for your help!
Change this
System.out.print(reversDigits(9876548));
to
reversDigits(9876548);
Use this way
public static void main (String [] args)
{
reversDigits(9876548);
}
public static int reversDigits(int number) {
int result;
if (number < 10) {
System.out.println(number);
result = number;
}
else{
System.out.println(number % 10);
reversDigits(number/10);
result = number;
}
return result;
}
I am trying to get all prime factors of a number. The for loop should work until it finds the match and it should break and jump to the next if statement which checks if number is not equal to zero.
public class Factor {
public static ArrayList <Integer> HoldNum = new ArrayList();
public static void main(String[]args){
Factor object = new Factor();
object.Factor(104);
System.out.println(HoldNum.get(0));
}
public static int Factor(int number){
int new_numb = 0;
int n=0;
for( n = 1; n < 9; n++) {
if (number % n == 0) {
HoldNum.add(n);
new_numb = number/n;
break;
}
}
System.out.println(new_numb);
if(new_numb < 0) {
HoldNum.add(new_numb);
return 1;
} else {
return Factor(new_numb);
}
}
}
There are at least three errors :
As okiharaherbst wrote, your counter is not incremented.
you start your loop at 1, so yourval % 1 always equals to 0 and new_numb is always equals to your input val, so you'll loop endlessly on 104.
new_numb will never be lesser than 0.
You asked for a recursive solution. Here you go:
public class Example {
public static void main(String[] args) {
System.out.println(factors(104));
}
public static List<Integer> factors(int number) {
return factors(number, new ArrayList<Integer>());
}
private static List<Integer> factors(int number, List<Integer> primes) {
for (int prim = 2; prim <= number; prim++) {
if (number % prim == 0) {
primes.add(prim);
return factors(number / prim, primes);
}
}
return primes;
}
}
The code is not bullet-proof, it is only a quick-and-dirty example.
Java implementation...
public class PrimeFactor {
public int divisor=2;
void printPrimeFactors(int num)
{
if(num == 1)
return;
if(num%divisor!=0)
{
while(num%divisor!=0)
++divisor;
}
if(num%divisor==0){
System.out.println(divisor);
printPrimeFactors(num/divisor);
}
}
public static void main(String[] args)
{
PrimeFactor obj = new PrimeFactor();
obj.printPrimeFactors(90);
}
}
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