I did go through the other threads on this SPOJ problem, ADDREV (Adding Reversed Numbers), but sadly, I was not able to get an answer by any of the three programs that I have written (in C, Python and Java). I am attaching the code snippets of all three.
Python:
def find_rev(a):
d=0
while(a>=1):
d=d*10+a%10
a=a/10
return d
n=input('enter a number')
for i in range(int(n)):
num1=input('enter the first number')
num2=input('enter the second number')
num=0
num1=find_rev(int(num1))
num2=find_rev(int(num2))
num=num1+num2
num=find_rev(num)
print num
With Python, I get a runtime error.
With C, I get a wrong answer.
#include<stdio.h>
long rev(long);
int main()
{
long int n;
long int n1;
long int n2;
long int i=0;
scanf("%ld",&n);
//printf("%d",n);
for (i=0;i<n;i++)
{
//printf("\n%d",i);
//printf("\nenter the two numbers");
scanf("%ld%ld",&n1,&n2);
n = rev(rev(n1)+rev(n2));
printf("%ld\n",n);
}
return 0;
}
long rev(long a)
{
long d=0;
while(a>=1)
{
d = d*10+a%10;
a = a/10;
}
return d;
}
With Java, I get a compilation error.
import java.util.*;
//import java.io.*;
public class spoj_prob {
public static void main(String args[])
{
long n=0;
System.out.println("enter a number \n");
Scanner in=new Scanner(System.in);
n=in.nextLong();
long n1=0;
long n2=0;
long sum=0;
for (int i=0; i<n; i++)
{
System.out.println("enter two numbers \n ");
n1=in.nextLong();
n2=in.nextLong();
n1=rev(n1);
n2=rev(n2);
System.out.println(n1);
System.out.println(n2);
sum=rev(n1+n2);
System.out.println(sum);
}
}
static long rev(long a)
{
long d=0;
while (a>=1)
{
d=d*10+a%10;
a=a/10;
}
return d;
}
}
}
Of course, those errors are reported by the SPOJ Judge. The programs work fine on my system. Test cases I use are:
2
999999999 11
999 11
Answer
101
101
Also
3
34 54
123 091
00034 00054
Update: Guys, I got the answer in C. Thank you for all the help.
Before you start using any service, it's generally a good thing to read its FAQ. It explains how exactly the program should receive data.
In particular, please notice that printing enter a number and other junk to the console will always lead to a wrong answer. Because a correct program would output something like
34
1998
1
and yours
enter a number
enter two numbers
34
enter two numbers
1998
enter two numbers
1
I can't tell why Java fails to compile, though. You probably should find some information on how to submit in Java with the reference solution.
Also, the problem definition gives no limit for input numbers, so they can possibly be too big for standard integer types in Java and C++.
With Python I think you're getting Runtime Error because you're calling a restricted function input, nothing else comes to mind.
In C you're getting WA because the input integers can be very large, and you're overflowing.
For JAVA there are 2 potential problems that you may have. One is that you're using Scanner class which may not be supported by SPOJ (due to security or other considerations). Second, is that your class name needs to be Main I think. Please search SPOJ forum for more details on this.
Try this solution in Python 3:
import sys
t = int(input())
i=0
while i<t:
a,b = map(int,sys.stdin.readline().split()) #to take both inputs in single line
c=str(a) #converting the number into string
d=str(b)
e=int(c[::-1]) #converting reverse of the string c to int
f=int(d[::-1]) #converting reverse of the string d to int
s=e+f #adding the two reverse numbers
s1=str(s)
s2=int(s1[::-1]) #reverse s and display it
print(s2)
i+=1
Related
I got to calculate the factorial of a number. As a fact factorial of 0 is 1. So I included that case in the function as well.
here's the code:
import java.util.*;
public class Factorial {
static int fact(int n) {
int result;
if (n == 0 || n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
public static void main(String args[]) {
int i, fact = 1;
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
}
but if I'm giving input as 0, some exception was raised
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
at java.util.Scanner.nextInt(Scanner.java:2117)
at java.util.Scanner.nextInt(Scanner.java:2076)
at Factorial.main(Factorial.java:14)
How to resolve this situation?
Edits:
I have changed the exception.All apologies for the thing that yes the code wasn't even 26 lines. I had put some code above as comments before posting just the code here.
This ain't a duplicate. As of the fact I want to know why it doesn't accept 0 as an input. It works perfect for all other inputs.
I use an online Compiler https://www.tutorialspoint.com/compile_java_online.php
Works fine with Java Compiler of the PC JDK 1.7 ,but raises exception on online IDE.
NoSuchElementException will be thrown if no more tokens are available. This is caused by invoking nextInt() without checking if there's any integer available. To prevent it from happening, you may consider using hasNextInt() to check if any more tokens are available. Link.
Modified your code and added hasNextInt so that NoSuchElementException is not thrown and sc.close() to close the resource at the end of main method
public static void main(String args[]) {
int fact = 1;
Scanner sc = new Scanner(System.in);
if (sc.hasNextInt()) {
int n = sc.nextInt();
fact = fact(n);
System.out.println(fact);
}
sc.close();
}
The online IDE is probably doing some kind of pre-processing of the data that
don't plays very nice with zeros.
TutorialPoint has online compilers for multiple languages and is very likely
that these all share some common backend that does the magic of passing text
from your browser to their servers. I'm not sure what kind of processing is
happening behind but I can imagine that is something like trimming the
unnecessary zeros from the left of the numbers or something like that.
I have encountered the opposite problem in standard C with the function sscanf,
which expected to fail (return 0) when the input string is empty just like its
sister function scanf but it still returns sucess and stores zero in the integer
variables.
By the way, if you just add a leading space or \n to the zero, everything works
just fine.
Im trying to create a method to find the common factors of 2 given numbers but I can not get the file to compile. All of my curly brackets are closed as I'm aware thats usually almost always the cause of this error. Hopefully someone can help me out!
import java.util.Scanner;
public class E1{
public static void main (String [] args){
Scanner kb = new Scanner(System.in);
double n1,n2;
System.out.println("Enter two numbers");
n1=kb.nextDouble();
n2=kb.nextDouble();
printCommonFactors(n1,n2);
}
//call a method that prints the positive shared factors of the 2 inputed numbers
public static void printCommonFactors(int n1,int n2){
//determining the max/min of the two inputed variables
int max,min;
max=Math.max(n1,n2);
min=Math.min(n1,n2);
//setting up 2 arrays to store the factors
int [] maxFactors = new int [max];
int [] minFactors = new int [min];
int counter1;
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (int i=0;i>min;i++)
if (maxFactors[i]%min=0)
maxFactors[i]=
}
}
This is the error I receive:
The reason you are seeing the "reached end of file while parsing" is that the parser expects to find a right-hand-side operand for the equals operator but fails to do so. You end your method with maxFactors[i]=. Binary operators always require right-hand-side operands. In this case, you must place a value after the equals-sign.
Also, it looks like you are trying to apply some principles to Java that you probably pulled from another language. The most obvious one here is that you use replace explicit blocks with white-space. This works for languages like Python, but does not work in Java. Indentation is not significant in Java and only has the effect of improving readability.
This is relevant for your for statements. Because you are not actually using blocks, these statements are actually equivalent:
for (inti=0;i>max;i++)
if (i%max=0)
counter1++;
maxFactors[counter1]=i;
for (inti=0;i>max;i++) {
if (i%max=0) {
counter1++;
}
}
maxFactors[counter1]=i;
This will cause issues with i being referenced out of its scope. The other issue with this is that the for initializer (inti=0;) is missing a space and should be int i = 0.
Other issues include trying to allocate arrays with a non-integer size (must be of type int) and using bad test expressions for your for-loops (i>min will invariably remain true if it is ever true due to your incrementor until an integer overflow is reached).
I've try to use long and double with c, k, n variables but netbeans shows me a stack overflow error:
public class Main {
public static void main(String[] args) {
double c=0; //combinatorial
double n=5;
double k=15;
c= factorial(n)/(factorial(k)*factorial(n-k));
System.out.print(n+" combinatorial "+k+" between "+c+"\n");
}
static double factorial (double number) {
if (number == 0)
return 1;
else
return number * factorial(number-1);
}
}
Exception in thread "main" java.lang.StackOverflowError
at co.combinatorial.Main.factorial(Main.java:26)
at co.combinatorial.Main.factorial(Main.java:29)
at co.combinatorial.Main.factorial(Main.java:29)
at co.combinatorial.Main.factorial(Main.java:29)
......
Java Result: 1
Do I have to use integer literals or long.parselong
What I am doing wrong?
From the initial values, n-k = -10. Since this is less than 0, your factorial method will never return
(number == 0) may not happen due to binary representation of number. Even with some tolerance level added, it is still incomplete this way. You may need negative number conformance. (10-10 maybe not zero)
Each time it goes deeper in function stack because of recursivity, it consumes more memory for function variables and parameters until java cannot plea more from operating system.
c= factorial(n)/(factorial(k)*factorial(n-k));
For n=5 and k=15,
factorial(n-k) would become: factorial(-10)
and then..
number*factorial(number-1) would give us: -10*factorial(-11),
and like this it would
continue indefinitely never reaching 0.
hence the stack will overflow.
Right, I am working on a program for school the purpose of the program is to find the minimum number of coins, I am a novice programmer and this is my first time so I dont know the thousands of other things and what not other people do. I wrote the code and it works, but I seem to have found a bug/glitch or w/e you want to call it.
my code
import java.util.Scanner;
public class Coin {
public static void main (String[] Args) {
int quarters = 25;
int dimes = 10;
int nickles = 5;
int pennies = 1;
System.out.println("Enter in a number between 1-99");
// "Input" Part of Code (Remember this and go back for reference)
Scanner Userinput = new Scanner(System.in);
int stuff = Userinput.nextInt();
int q = stuff/quarters;
String A = "Number of Quarters:" +q;
System.out.println(A);
int hold = stuff%quarters;
int d = hold/dimes;
String B = "Number of Dimes:" +d;
System.out.println(B);
int hold1 = stuff%dimes;
int n = hold1/nickles;
String C = "Number of Nickles:" +n;
System.out.println(C);
int hold2 = stuff%nickles;
int p = hold2/pennies;
String D = "Number of Pennies:" +p;
System.out.println(D);
System.out.println("Thank you for Using My Program");
}
}
Now, everything works fine I can input any number I like and get the desired result, however for some odd reason I cannot fathom I type in any number between 75-79 and there is an added Nickle for some odd reason and I have spent the better part of 2 hours trying to figure out exactly what is wrong but cannot. Hav tried dozens of toher numbers and they work fine except for that one little area.
Can someone tell me by chance what might be wrong?
Your hold = ... lines should be based on the previous hold value rather than the full amount (stuff).
int hold2 = hold%nickles;
You need to subtract off what has already been accounted for when adding previous, larger coins.
For example, if I say 77, then the program will check 77%10 and return 7. You would want to adjust your "stuff" value by any previously added coins. So in this case, after adding 3 quarters (75) we would want to set stuff = stuff - 75 (stuff -= 75).
EDIT: to be more precise, after every calculation you could run
stuff -= q * quarters;
of course, changing the variables to be appropriate for each part of your code.
this is basically my first true Java assignment and I've hit a brick wall. I basically wrote my entire project as if the user were to input the information into the program. upon rereading the assignment I saw that we are to input the info from a .txt file in the following format:
1.17 12 15( and then sort them)
7 54 9873 1867 4425 878 365 783 (where the first number n indicates how many n will folow)
4 (flyods triangle problem)
20 (fizz buzz problem)
I have all of the code written to solve these parts of the project but am completely stuck on how to implement the numbers from the .txt file. I am not asking for code merely some advice on how you guys might go about doing so/
import java.util.Arrays;
import java.util.Scanner;
public class FunTime {
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
n = in.nextInt();
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
System.out.println();
}
Fortunately, reading from a file is exactly like reading from the terminal. Instead of reading from System.in, read from a file that you open with something like FileInputStream.