Error in test cases for a recursion problem - java

I am solving a code for competitive programming and my code which I think is correct is throwing an error for some test cases:
The question is to find the total number of digits in an integer using recursion.
My Code:
import java.util.*;
import java.io.*;
import java.lang.*;
class Driver_class
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0)
{
int n =sc.nextInt(); // taking number "n" as input
System.out.println(new Digitcount().countDigits(n)); // prints the count of digits
}
}
}
class Digitcount
{
static int count=0;
public static int countDigits(int n)
{
if(n<1)
return 0;
countDigits(n/10);
count++;
return count;
}
}
The count variable is the total number of digits.
The test case that this code fails:
However, this code passes all the test cases:
class Digitcount
{
static int count=0;
public static int countDigits(int n)
{
if(n<1)
return 0;
return countDigits(n/10)+1;
}
}
I dont see a difference in any of my codes regarding the output value. What is causing the first code to fail the test case?

The difference is in use of a static variable. It will hold the result between tests and thus in any test after the first one it will be incorrect. If you have two calls one after the other like so:
int a = countDigits(605);
int b = countDigits(605);
The result will be a==3, b==6 - the first result is carried over to the second call.

Related

Big Integer Java

Why is my code printing the output 4 times? The answer is correct but the answer is printed 4 times instead of the desired one time.
import java.util.*;
import java.math.BigInteger;
class THIRTYSEVEN
{
static Scanner sc = new Scanner(System.in);
public static void main(String[] args)
{
BigInteger a = new BigInteger("1");
multiply(a,0,sc.nextInt());
}
static void multiply(BigInteger b, int loop, int power)
{
BigInteger result = b;
while(loop<power)
{
result = result.multiply(new BigInteger("8"));
loop++;
multiply(result,loop,power);
}
System.out.println(result);
}
}
You call multiplyonly once, but it recursively calls itself (and prints every time). You could return the result instead (and print it from main).

NZEC Prime number Generation SPOJ- http://www.spoj.com/problems/PRIME1/

I am beginner at coding. I am getting NZEC error on submission of my code for prime number genertaion to spoj. But the code is working perfectly fine in my desktop. Kindly help me. This is what i have coded.
import java.util.*;
import java.lang.*;
import java.io.*;
import static java.lang.Math.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
int testcase;
int lower_limit,upper_limit;
int i,j,k;
boolean[] a= new boolean[100001];
Arrays.fill(a, Boolean.TRUE);
Scanner sc1 = new Scanner(System.in);
testcase= sc1.nextInt();
for(;testcase>0;testcase--)
{
lower_limit= sc1.nextInt();
upper_limit= sc1.nextInt();
for(i = 2;i<sqrt(upper_limit);i++)
{
if(a[i]=true)
{
for(j=i;j<=upper_limit;j=j+i)
{
a[j]=false;
}
}
}
for(i=lower_limit;i<upper_limit;i++)
{
if(a[i]==true)
{
System.out.println(i);
}
}
}
}
}
Your array goes out of index for large values of m and n. Try this sample test case on your system where m = 999900000 and n = 1000000000. You can't store these large values as the index of the array. Even m or n = 10^8 will go out of bound index for an array.

prime numbers test in java

I have an assignment that tells me to do the following:
Create a method named IsPrime(), which accepts a positive integer as a parameter. If a number if prime, the method should return true. (A prime number is evenly divisible only by 1 and itself). Incorporate this method into a class named MyMathMethods. Create a main() method in a separate class called MainFile, which will test IsPrime() by asking the user for a number using an input dialog and will then report whether that number is prime or not.
How do I connect these two files?
here is my code:
package x;
import java.util.Scanner;
public class MyMathMethod
{
public static boolean isPrime(int num)
{
int result=0;
System.out.println("enter no");
Scanner s = new Scanner(System.in);
num =s.nextInt();
long sqrt = (int) Math.sqrt(num);
for(long divisor = 2; divisor <= sqrt; divisor++)
{
if(num % divisor == 0)
{
// This only needs to happen once
// for this number to NOT be prime
return false;
}
}
// If we get here, the number is prime.
return true;
}
}
Another File is
import x.*;
package y;
public class MainFile {
public static void main(String [] args) {
boolean isNumberPrime;
int num;
MyMathMethod methods = new MyMathMethod();
isNumberPrime = methods.isPrime(num);
{
if(num=true)
System.out.println(num + " is Prime Number");
else
System.out.println(num + " is not Prime Number");
}
}
}
Thanks in advance.
Do you want to call the method isPrime() from your main in another class?
When they're a in the same package, you have to create a new instance of your class MyMathMethods and call the method isPrime(). when they're in different class, you must import the missing class and do the same as above. If you don't import it manually, probably your IDE will do it for you or ask for it.
the first file:
package x;
public class MyMathMethods {
public boolean isPrime(int number) {
//your code here
return false;
}
}
the second:
package y;
import x.* //importing all files from the package x
//if your class MyMathMethods is in the same package, you don't need that
public class MainFile {
public static void main(String [] args) {
int number = 20;
boolean isNumberPrime;
MyMathMethods methods = new MyMathMethods();
isNumberPrime = methods.isPrime(number); //here the result if it's prime
}
}
EDIT: I'll try to fix your code.
If you want to have your method static, you can call it:
MyMathMethods.isPrime(numer);
without the need to create a new instace.
The next issue: why are you passing to the funtion a variable that is not initialized (num) and try to get this value from the input in this method? Well, that's not a good practise. I would rather suggest to get the input from the user in main (directly in main on in another function called up in main) and then pass the value to isPrime().
package y;
import x.*
public class MainFile {
public static void main(String [] args) {
int num;
Scanner s = new Scanner(System.in);
num =s.nextInt();
if(MyMathMethods.isPrime(num)) {
//if true, your code;
} else {
//false, your code;
}
}
}
package x;
public class MyMathMethod {
public static boolean isPrime(int num) {
if (num <= 1) {
return false;
}
for (int i = 2; i < Math.sqrt(num); i++) {
if (num % i == 0) {
return false;
}
}
return true;
}
}
Your algoritm failed for many numbers, e.g. 0, 1, 2. Well, for this values it doesn't even returned any value. Please always protect your method against any possible wrong parameters.

to find out big factorial n count the number of zeros at the end

this is my java code :
import java.util.Scanner;
import java.math.*;
abstract class ccFctrl {
public static long countZero(BigInteger a){
long noOfZero=0;
long b;
do{
b =noOfZero;
if(a.remainder(BigInteger.TEN)==BigInteger.ZERO){
noOfZero++;
}
a.divide(BigInteger.TEN);
}while((noOfZero!=0)&&(noOfZero!=b));
return noOfZero;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner s=new Scanner(System.in);
int numOfFctrlsToCalculat=s.nextInt();
BigInteger fctrl=new BigInteger("1");
BigInteger inc=new BigInteger("1");
int num;
long[] count=new long[numOfFctrlsToCalculat];
System.out.println();
for(int i=0;i<numOfFctrlsToCalculat;i++){
num=s.nextInt();
for(int j=1;j<=num;j++){
fctrl=fctrl.multiply(inc);
inc=inc.add(BigInteger.ONE);
}
inc=BigInteger.ONE;
count[i]=countZero(fctrl);
System.out.println();
}
for(int i=0;i<numOfFctrlsToCalculat;i++){
System.out.println(count[i]);
}
s.close();
}
}
IDE on compiler is constantly showing me error. just can't get why code is not running
Two things:
You are going into infinite loop in your method countZero. Remember BigInteger is immutable, so doing operation on the same, you should reassign the value like:
a = a.divide(BigInteger.TEN);
Your condition will never get satisfied because of above and hence will lead to infinite loop. You should check for below condition:
} while (!a.equals(BigInteger.ZERO));
Note Aside: Any reason for defining your class as abstract?
This is known programming contest problem.
Descrition is here for example.

Fibonacci Sequence return argument

I need to generate a program that generates the Fibonacci Sequence
Here is what I have so far:
import java.util.Scanner;
public class FibonacciRunner
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.println("Enter n:");
int n = in.nextInt();
EP64 fg = new EP64();
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber());
}
}
public class EP64
{
public static void nextNumber(int n)
{
int fold1 = 1;
int fold2 = 1;
int fnew = fold1 + fold2;
fold1 = fnew;
}
}
I get an error on:
System.out.println(fg.nextNumber());
saying:
method nextNumber in class EP64 cannot be applied to given types:
required: int
found: no arguments
reason: actual and formal argument lists differ in length
and can someone also tell me if I am doing this program right? If not, help! I looked at other similar questions but I cannot make much sense of them
Thank you all!
method nextNumber in class EP64 cannot be applied to given types: required: int found: no arguments reason: actual and formal argument lists differ in length
Your
public static void nextNumber(int n)
^^^^^^^
says that any call to the method must provide an integer as argument. But here:
System.out.println(fg.nextNumber());
^^ you need to add an integer argument
you violate this by providing no argument.
As your code reads now, I'd probably drop the int n argument.
and can someone also tell me if I am doing this program right?
Naah, not really...
fold1 and fold2 should probably be member variables (so they don't get reset in every call to the method),
You're forgetting to update fold2 (you only update fold1),
Also, you probably want to return an int from the nextNumber method.
Read up on
Official Java Tutorial: Defining Methods
You are calling a static method to a object reference instead of the class itself.
And
Not passing any argument at all for nextNumber() method.
Make the method non-static as :
public void nextNumber(int n) {}
Pass arg to the method as :
for (int i = 1; i <= n; i++)
System.out.println(fg.nextNumber(n));
And also don't forget to return the processed number from your nextNumber method,which you collecting in System.out.println.
Your declaration of nextNumber says it takes an int argument, but you are calling it with no arguments.
Also, your code isn't going to do what you want. You probably should make fold1 and fold2 members of class EP64 and make the method an instance method rather than a static method. You also need to do fold2 = fold1; before you update fold1.
Finally, you need to declare nextNumber to return an int value, and then actually have it return an int value.
You have two problems. Firstly, your method doesn't return anything, i.e. it is void. You need to make it int and add a return fnew; at the end. The other problem is you are starting from scratch every time, it will return 2 each time. You need to make fold1 and fold2 fields by moving them above the nextNumber line. Oh, and drop the int n argument as it doesn't do anything.
I agree on the diagnostics of the other posts, but don't suggest a member variable, but a rename and local variables.
You can ask for the 5th Fibonacci-Number with 5 calls to
fib.next ();
or with a single call to
fib (5);
Since the fibonacci-sequence increases very rapidly, you have very few calls (54) before hitting the overflow boundary. So if you repeatedly recalc the same sequence, to print the sequence, it's not a big problem. A recursive solution would be fine.
Btw.: EP64 is a very bad name.
I think this is enough:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
int a=0,b=1,c;
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
If you want to call this as a method then:
import java.util.Scanner;
public class Fibnocci
{
public static void main(String []abc)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter the Range: ");
int n= in.nextInt();
callFibonocci(n);
}
public static void callFibonocci(int n)
{
int a=0,b=1,c;
System.out.print(a+" "+b);
for(int i=0;i<n-2;i++) //n-2 because we are showing 0,1 initially.
{
c=a+b;
System.out.print(" "+c);
a=b;
b=c;
}
}
}
You can call this method out of the class;
// Fibnocci Using c#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CodeProject
{
class FibnocciSeries
{
public int[] FibonacciArray(int length)
{
int[] fseries = new int[length];
fseries[0] = 0;
fseries[1] = 1;
if (length == 0)
return null;
//Iterating through the loup to add adjacent numbers and create the memeber of series
for (int i = 2; i < length; i++)
{
fseries[i] = fseries[i - 1] + fseries[i - 2];
}
return fseries;
}
}
}
////////////////////
class Program
{
static void Main(string[] args)
{
FibnocciSeries fb = new FibnocciSeries();
Console.WriteLine("Please Enter Integer Length of Fibnocci series");
int length = Convert.ToInt32(Console.ReadLine());
int[] result = fb.FibonacciArray(length);
foreach(int i in result)
Console.Write(i.ToString()+ " ");
Console.ReadLine();
}
}
|

Categories