This code compiles fine, but when I run it, it asks for my two numbers as expected and then just sits there and doesn't do anything at all. I've searched the Internet and worked on this all day. I'm finally caving and asking for help.
Is the issue that it's not looping back up automatically? After 10 hours at this, I've found nothing.
import java.util.Scanner;
public class EA
{
public static void main (String[] args)
{
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
//do the calculations
while(J>0)
{
int Remainder;
Remainder = I % J;
while(Remainder>0)
{
I = J;
J = Remainder;
return;
}
System.out.println("GCD is" + J);
}
}
}
}
Among other things already mentioned, you are confusing while with if. You have put your algorithm logic inside a while loop that only runs if the first input is bad.
// get first integer from user
Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
//resolve the issue of zero
while(J<1)
{
// You never reach here under ordinary conditions
}
SJuan mention that the return breaks the loop, which is true, but even if it's fixed there are a few other issues:
The inner while never end (infinite loop)
The result will be stored in J - not in I
System.out.println("GCD is " + I); Should be printed outside of the outer while!
The "heart" of your program should do this:
// we get here with valid values stored in I,J
int Remainder = I % J;
//do the calculations
while(Remainder>0)
{
I = J;
J = Remainder;
Remainder = I % J;
}
System.out.println("GCD is " + J);
There are more than 1 error: the return in the while, the algorithm and the brackets of the first while.
1) When you resolve the issue of zero, the brackets of the while must be closed suddenly after you re-assign the value of the variable J.
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
2) The algorithm for computing the gcd is the following:
function gcd(a, b)
while b ≠ 0
t := b
b := a mod t
a := t
return a
Here is the correct version of your code:
public static void main(final String[] args) {
// get first integer from user
final Scanner input = new Scanner(System.in);
System.out.println("Please enter the larger integer: ");
int I;
I = input.nextInt();
// get second integer from user
System.out.println("Please enter the smaller integer: ");
int J;
J = input.nextInt();
// resolve the issue of zero
while (J < 1) {
System.out.println("Can not divide by zero!");
System.out.println("Please enter new smaller integer: ");
J = input.nextInt();
}
// do the calculations
while (J != 0) {
int Remainder;
Remainder = I % J;
I = J;
J = Remainder;
}
System.out.println("GCD is" + I);
}
The return in the middle of the loop will end the execution.
This one
while(Remainder>0)
{
I = J;
J = Remainder;
return; <------- THIS IS THE RETURN THAT BREAKS ALL
}
so it does not get to the System.out.println.
UPDATE: Also, you do input.nextInt() twice for J. Probably from your description, it keeps waiting for you for entering the third integer.
Well Euclid's algorithm has a drawback as both the inputs should be non zero to compute the Greatest common divisor . But if you want to find out the GCD when one of the input is a zero ('0') tweak the logic a bit . When one of the input is zero the GCD is 1, and 'a' should be greater than 'b' to compute GCD. Check the snippet below:
if (a < b) {
int temp = a;
a = b;
b = temp;
}
if (b == 0) {
System.out.println("1");
} else {
while (b != 0) {
r = a % b;
a = b;
b = r;
}
Related
I've been stuck on this code for a couple of hours.
The sum is S = 1-x + x^2 - x^3 + x^4.
We ask for X and N with starting value of i = 0.
Whenever the previous exponent (i) is odd we add x^i, and
if the previous exponent is even we subtract x^i.
I've put them on a loop but i can't seem to get the sum correctly.
Can anyone tell me what I'm doing wrong?
Thank you!
import java.util.Scanner;
public class hw1 {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int X = scan.nextInt();
System.out.println("Enter number N");
int N = scan.nextInt();
int sum = 0;
for (int i = 0; i <= N; i++) {
if (i < N) {
if (i % 2 != 0) // if I is even
{
sum = sum - (X ^ i);
} else // if I is odd
{
sum = sum + (X ^ i);
}
}
}
System.out.println("Z is " + sum);
}
}
}
So I fixed a few things in your code:
I switched the ^ operator (which, as #Nick Bell pointed out, is a bitwise exclusive OR) for Math.pow.
I fixed the spelling of your variables x and n. In Java, convention is to give variables names that start with lower-case. Upper-cases (X and N) are reserved for constants (fields marked final) and for classes (as opposed to objects). Note that this is only a convention, and that the code works fine both ways. It just helps in reading the code.
Your odd/even check was inverted: x % 2 == 0 is true for even numbers.
The reason that you inverted your odd/even check was probably the two operations on sum were inverted. Compare with the description of your problem in the first paragraph of your question, you'll see where you went wrong.
The if i < N check was redundant. It you really wanted to limit computation to i < N, you should specify it directly in your first for loop.
I added two try/catch blocks with infinite loops that break when an integer is entered, because your previous code threw an exception and stopped if you entered something else than a well-formed integer (such as letters, or a decimal value). Up to you to keep them or delete them.
By the way, initializing x and n to 0 is now redundant, since your code is guaranteed to assign them another value right away.
This is the updated code.
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
System.out.println("Sum = 1^0-x^1+x^2-x^3..+x^n");
System.out.println("Enter number X");
int x = 0;
while (true) {
try {
x = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
System.out.println("Enter number N");
int n = 0;
while (true) {
try {
n = Integer.parseInt(scan.nextLine());
break;
} catch (NumberFormatException e) {
System.out.println("Enter an integer.");
}
}
double sum = 0;
for (int i = 0; i <= n; i++) {
if (i % 2 == 0) // if I is even
sum = sum + Math.pow(x, i);
else // if I is odd
sum = sum - Math.pow(x, i);
}
System.out.println("Z is " + sum);
}
}
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 am trying to make a program where a user enters 2 numbers, and then the program gives the tau numbers in this gap.
"Tau" number is the number which can divided by its total number of dividers.For example (1,2,3,4,6,8,12,24) all this numbers can divide 24. There is 8 numbers then 24 can divided by 8. So we can say 24 is a tau number.*
There is a mistake at second for loop I think but I cannot understand where is it.
import java.util.Scanner;
public class tauNumber {
public static void main(String [] args){
int start=0,stop=0,count=0;
Scanner input =new Scanner(System.in);
System.out.println("Please enter first number: ");
start=input.nextInt();
System.out.println("Please enter last number: ");
stop=input.nextInt();
for(int i=0+start;i<=stop;i++){
for(int j=1;j<=start;j++){
if(i%j==0){
count++;
}
}
if(start/count==0){
System.out.println(i+" is a tau number" );
}
}
}
}
Instead of saying "tau number" you should just refer to it as a refactorable number as #Tunaki pointed out.
I would suggest that you split your code up into functions to get a better understanding on whats going on, I think this is what you're looking for:
import java.util.Scanner;
class TauNumber {
public static void main(String[] args){
Scanner input =new Scanner(System.in);
System.out.println("Please enter first number: ");
int start=input.nextInt();
System.out.println("Please enter last number: ");
int stop=input.nextInt();
for(int i=start+1; i<stop; i++){
if(refractorable(i)){
System.out.println("Found tau number: "+ i);
break;
}
}
}
public static boolean refractorable(int number){
if(sumDivisors(number) == 0) return false;
if(number % sumDivisors(number) == 0){
return true;
} else {
return false;
}
}
public static int sumDivisors(int number){
int sum = 0;
for(int i=1; i<=number; i++){
if(number % i == 0){
sum++;
}
}
return sum;
}
}
Note: I would also like to point out that when you specify "gap" what do you mean by it? I took it as start < x < stop, because that would be the gap but it could certainly be start < x <= stop.
The fault in your code is that you check whether the quotient of start/count is 0. To check whether start is divisible by count, you should check whether the remainder is 0. Therefore, you should use the modulus (%) operator instead of the division (/) operator.
Below is a function's code that checks whether its argument is a tau number.
private static boolean isTau(int tau){
int count = 0;
for(int i=1; i<=tau; i++){
if(tau % i == 0)
count++;
}
return (tau % count == 0) ; //returns true if 'tau' is a tau number
}
In the main method, you can make use of this function like this:
for(int i=start; i<=stop; i++){
if(isTau(i))
System.out.println(i+" is a tau number");
}
I need to write a program which accepts non-negative double type of
numbers as
income amounts one by one unti
l a negative number
is entered
, and the negative number ends the
program. When the program is completed by entering a negative number
, it prints out the
minimum, average, and maximum for the set of entered incomes (excluding the last negative
number
be
cause it only indicates the end of user input).
package incomeapp;
import java.util.Scanner;
/**
*
* #author Kenneth
*/
public class IncomeApp {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
int count = 0;
double i = sc.nextDouble();
while (i > 0){
double nextDouble;
nextDouble = sc.nextDouble();
if (i < 0){
break;
}
}
}
}
There's a few issues with your code here:
You never actually increment either sum or count
You read input into i before the loop, but then you read into nextDouble inside the loop and the loop condition only checks i - which never changes.
You never print out the minimum, average, and maximum
The condition in the while and if statements are redundant (apart from the if condition accepting 0 which the while condition doesn't)
Now, this seems very much like a programming assignment to me so I'm not going to post the complete code for you. Here's what you should do to fix your code though:
Increment sum and count in the loop.
Use either i or nextDouble - not both.
Print the desired output after the loop
Pick one way of terminating the loop. Here's two ideas on how to do it:
double i = sc.nextDouble();
while (i > 0) {
// Do something with i
i = sc.nextDouble();
}
or
while (true) {
double i = sc.nextDouble();
if (i <= 0) {
break;
}
// Do something with i
}
Try this:
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner sc = new Scanner(System.in);
System.out.print("Enter an income (any negative number to quit: ");
double sum = 0;
double max = 0;
double min = Double.MAX_VALUE;
int count = 0;
double nextDouble;
while (sc.hasNext()) {
nextDouble = sc.nextDouble();
max = Math.max(max, nextDouble);
if (nextDouble < 0){
break;
}else {
min = Math.min(nextDouble, min);
sum += nextDouble;
count++;
}
}
System.out.println("Average: " + sum/count);
System.out.println("Min: " + min);
System.out.println("Max: " + max);
}
}
UPDATED
How can you by using this method (Collatz conjecture) to find the number with the highest number of operations between, say 4 and 230.
Any guidance appreciated.
public static void main(String[] args) {
System.out.print("Enter a low integer ");
Scanner input = new Scanner(System.in);
int low = input.nextInt();
System.out.print("Enter a high integer ");
int number = input.nextInt();
maxendurance(number);
}
public static int maxendurance(int number) {
int count = 0;
System.out.print("The number " + number);
// need to loop this i suppose in relative to user input
while (number != 1) {
number = (number & 1) != 0 ? number * 3 + 1 : number >> 1;
count++;
}
System.out.println(" has endurance: " + count);
return number;
}
You will have to loop through all the numbers between low and high. Look into for-loops:
for(int number = low; number <= high; number++)
{
// do something with number
}
Somehow you will need to execute a for every number within the loop (hint: pass it in as a parameter). Then keep track of the number with the highest count.
Oh, and please name your methods more clearly than a and b - nobody will understand what they do without going through the code.
First of all, move the input out of method a:
public static void main(String[] args) {
System.out.print("Enter an integer to be checked: ");
Scanner input = new Scanner(System.in);
int number = input.nextInt();
a(number);
b();
}
public static int a(int number) {
int count = 0;
System.out.print("The number " + number);
[...]
Then you can use a simple for loop to iterate between low and high:
int bestNumber = -1;
int bestScore = -1;
for (int i = low; i <= high; i++) {
int score = a(i);
if (score < bestScore) {
bestNumber = i;
bestScore = score;
}
}
The result can then be found in bestNumber.
I am going to suggest a more advanced approach, in case relevant and incase anyone comes upon this. If you are concerned about time efficiency, Memoization or Dynamic Programming can help you, especially inverse dragon recursion.
I'll give you a hint. If you need more, just comment.
Take 3 for example. One transformation T has T(3)=10. If prior you had found it takes v transformations to take 10 to 1 and you stored (10,v) in a map, then instantly you know that it takes (v+1) steps to get 3 to 1.