Why java method is not working in loop - java

This is code to find armstorm numbers between given intervals. But when I put my my method in loop in main method so that it can run between given interval, then the loop only run one time and don't change the value passed to method. Why this is so? Is there is a difference in working of these conditions in different languages?
import java.util.Scanner;
class ArmstormNumbers {
int mod, div, count = 0, rev = 0, pow = 1, sum = 0;
int checkArm(int num) {
while(num!=0) {
mod = num%10;
div = num/10;
num = div;
count++;
rev = (rev*10) + mod;
}
while(rev!=0) {
mod = rev%10;
div = rev/10;
rev = div;
int temp = mod;
for(pow = 1; pow < count; pow++) {
mod = mod * temp;
}
sum=sum+(mod);
}
return sum;
}
}
class HelloWorld {
public static void main(String args[]) {
int num, arms, inp, fp, asm, num2;
Scanner input = new Scanner(System.in);
ArmstormNumbers object = new ArmstormNumbers();
System.out.println("This program will find armstorm numbers between two intervels");
System.out.println("Input Initial point ");
num = input.nextInt();
System.out.println("Input Final Point");
num2 = input.nextInt();
int temp = num;
for(num = temp; num <= num2; num++) {
asm = object.checkArm(num);
if(asm == num) {
System.out.println(num);
}
}
}
}

Move the variable declarations so that they become method-local variables which get initialised each time the method is executed, instead of only once when instantiating the object.
I.e. change
int mod,div,count=0,rev=0,pow=1,sum=0;
int CheckArm(int num)
{
to
int CheckArm(int num)
{
int mod,div,count=0,rev=0,pow=1,sum=0;
The problem you have and which you solve that way is probably relying on sum being 0 at start but not making that sure.

Related

How to write a strong number function in Java

enter image description hereI am trying to solve this question:
a) Write a method with the following header that takes an integer n and
returns the value of n! (pronounced n factorial) computed as follows:
public static int factorial(int n)
Note that 0! = 1 and n! = n * (n-1) * (n-2)*.....*1.
Example: factorial(4) will return 24 which is = 4*3*2*1.
b) Write a method with the following header that takes an integer x and
returns true if x is a Strong number. Otherwise, it returns false.
public static boolean isStrongNumber(int x)
Note that the isStrongNumber method should call the factorial method to compute the factorial of
each digit in x.
public static int factorial(int n) {
int f =1;
for (int i = 1; i <=n; i++)
f=f*i;
return f;
}
public static boolean isStrongNumber(int x) {
int temp = x;
int z;
int q = 0;
int sum = 0;
while (temp > 0) {
x = x % 10;
z = factorial(x);
q += z;
if (q == temp) {
System.out.print(q + " ");
return true;
}
}
}
This is my answer, but I get an error every time I try to run it.
You did not return boolean value at end of the isStrongNumber method
public static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i;
}
return result;
}
public static boolean isStrongNumber(int num) {
int originalNum = num;
int sum = 0;
while (num > 0) {
sum += factorial(num % 10);
num /= 10;
}
return sum == originalNum;
}
, main function
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a positive integer: ");
int number = Integer.parseInt(scanner.nextLine());
Set<Integer> set = new TreeSet<>();
for (int i = 1; i <= number; i++) {
if (isStrongNumber(i)) {
set.add(i);
}
}
System.out.println("The Strong numbers between 1 and " + number + " are:");
System.out.println(set);
scanner.close();
}
, output for input 100000
Enter a positive integer: 100000
The Strong numbers between 1 and 100000 are:
[1, 2, 145, 40585]
This cannot compile as it lacks a return statement outside the while loop. In fact, you cant be sure to go inside the loop even once if x<=0 for exmaple. You should add return false outside the loop at the end of the method. Also if you get an error and write a question on StackOverflow, copy the error message it's very helpful.

palindrome int in java

I tried to use some codes on Stack Overflow but when I used some codes,I didn't get the answer I want, this is my code now:
public class JavaApplication7 {
public static void main(String[] args) {
boolean answer = rev(1221);
if(answer == true) System.out.println("true");
else System.out.println("false");
}
static boolean rev(int number){
int reverse = 0, remain;
int num = number;
while(number > 0){
remain = number % 10;
reverse = (reverse * 10) + remain;
num = num / 10;
}
return number == reverse;
}
}
I want to check if palindrome is equal to the orginal int.
You have two bugs relating to confusing num (the local copy which you're modifying) and number (the parameter which you don't modify). I would make it final to make clear that the value is constant. And then use num consistently. I would also simplify the code a little. Like,
static boolean rev(final int number) {
int reverse = 0;
int num = number;
while (num > 0) {
reverse *= 10;
reverse += num % 10;
num /= 10;
}
return number == reverse;
}
And similarly in main, using an if to print true or false is pointless (and if you're going to do that use if (answer) - don't add unnecessary == true). But, I would prefer,
public static void main(String[] args) {
boolean answer = rev(1221);
System.out.println(answer);
}
Which outputs
true
Your rev function should be as below.
reversedInteger = 0, remainder, originalInteger;
originalInteger = num;
while( num != 0 )
{
remainder = num % 10;
reversedInteger = reversedInteger * 10 + remainder;
num /= 10;
}
static boolean rev(int number){
int reverse = 0;
int num = number;
while(number > 0){
reverse = reverse * 10 + number % 10;
number /= 10;
}
return reverse == num;
}

Number trailing zeros in factorial in java

import java.util.Scanner;
import java.io.*;
class factorial {
void fact(int a) {
int i;
int ar[] = new int[10000];
int fact = 1, count = 0;
for (i = 1; i <= a; i++) {
fact = fact * i;
}
String str1 = Integer.toString(fact);
int len = str1.length();
i = 0;
do {
ar[i] = fact % 10;
fact /= 10;
i++;
} while (fact != 0);
for (i = 0; i < len; i++) {
if (ar[i] == 0) {
count = count + 1;
}
}
System.out.println(count);
}
public static void main(String...ab) {
int a;
Scanner input = new Scanner(System.in);
a = input.nextInt();
factorial ob = new factorial();
ob.fact(a);
}
}
This code is work up to a = 10 but after enter number larger then a = 16 it gives wrong answer.
Please help.
As I am not able to post this question if I dont add more info for this question but I assume that the info I provide above is enough to under stand what I want.
Like many of these mathematical puzzles, you are expected to simplify the problem to make it practical. You need to find how many powers of ten in a factorial, not calculate a factorial and then find the number of trailing zeros.
The simplest solution is to count the number of powers of five. The reason you only need to count powers of five is that there is plenty of even numbers in between then to make a 10. For example, 5! has one 0, 10! has 2, 15! has three, 20! has four, and 25! has not five but six as 25 = 5 * 5.
In short you only need calculate the number of powers of five between 1 and N.
// floor(N/5) + floor(N/25) + floor(N/125) + floor(N/625) ...
public static long powersOfTenForFactorial(long n) {
long sum = 0;
while (n >= 5) {
n /= 5;
sum += n;
}
return sum;
}
Note: This will calculate the trailing zeros of Long.MAX_VALUE! in a faction of a second, whereas trying this with BigInteger wouldn't fit, no matter how much memory you had.
Please Note, this is not the mathematical solution as others suggested, this is just a refactoring of what he had initially...
Here I just used BigInteger in place of Int, and simplified your code abit. Your solution is still not optimal. I thought I would just show you what a refactored version of what you posted may look like. Also there was a bug in your initial function. It returned the number of zeros in the whole number instead of just the number of trailing zeros.
import java.math.BigInteger;
import java.util.Scanner;
class factorial {
public static void main(String... ab) {
Scanner input = new Scanner(System.in);
int a = input.nextInt();
fact(a);
}
private static void fact(int a) {
BigInteger fact = BigInteger.ONE;
int i, count = 0;
for (i = 1; i <= a; i++) {
fact = fact.multiply(new BigInteger(Integer.toString(i)));
}
String str1 = fact.toString();
for(int j = str1.length() - 1; j > -1; j--) {
if(Character.digit(str1.charAt(j), 10) != 0) {
System.out.println(count);
break;
} else {
count++;
}
}
}
}
Without using factorial
public class TrailingZero {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(trailingZeroes(9247));
}
public static int trailingZeroes(int a) {
int countTwo = 0;
int countFive = 0;
for (int i = a; i > 1; i--) {
int local = i;
while (local > 1) {
if (local % 2 != 0) {
break;
}
local = local / 2;
countTwo++;
}
while (local > 1) {
if (local % 5 != 0) {
break;
} else {
local = local / 5;
countFive++;
}
}
}
return Math.min(countTwo, countFive);
}}

Convert a base 10 number to a base 3 number

How to convert a base 10 number to a base 3 number with a method int converter(int num).
import java.util.Scanner;
public class BaseConverter {
int answer;
int cvt = 0;
while (num >= 0) {
int i = num / 3;
int j = num % 3;
String strj = Integer.toString(j);
String strcvt = Integer.toString(cvt);
strcvt = strj + strcvt;
num = i;
break;
}
answer = Integer.parseInt("strcvt");
return answer;
}
public static void main(String[] agrs) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a number: ");
int number = in.nextInt();
System.out.print(converter(number));
in.close();
}
It was Compilation completed. But when I tried to run it, and entered a number, it showed that
java.lang.NumberFormatException: For input string: "strcvt"
I don't know how to fix it. How can I do this without using string?
You shouldn't need to use String at all.
Try this instead
public static long asBase3(int num) {
long ret = 0, factor = 1;
while (num > 0) {
ret += num % 3 * factor;
num /= 3;
factor *= 10;
}
return ret;
}
Note: numbers in the computer are only ever N-bit i.e. 32-bit or 64-bit i.e. they are binary. However, what you can do is create a number that when printed at base 10, will actually appear to be the number in base 3.
"base 3 number" and "base 10 number" are the same number. In method int converter(int num) you're changing the number although you only need to change representation. Look at parseInt(String s, int radix) and toString(int i, int radix), that should help you.
you are not using variable declared String strcvt, instead due to typo mistake you have used as "strcvt"
change
answer = Integer.parseInt("strcvt");
to
answer = Integer.parseInt(strcvt);
You have to parse the value of strcvt not the string "strcvt"
So you have to remove the double qoutes answer = Integer.parseInt(strcvt);
And define the variable strcvt outside the loop.
change you code to:
public static int converter(int num) {
int answer;
int cvt = 0;
String strcvt = null ;
while (num >= 0) {
int i = num / 3;
int j = num % 3;
String strj = Integer.toString(j);
strcvt = Integer.toString(cvt);
strcvt = strj + strcvt;
num = i;
break;
}
answer = Integer.parseInt(strcvt);
return answer;
}

using methods to sum up numbers digits

This code is designed for summing up the digits of the number but it brings up
javac Root.java Root.java:17: error: '.class' expected
Who can explain what is the problem here. Also i want to make the same program using Arrays but i have problems with putting int in Array, if you have suggestions i am glade to here you.
import java.util.Scanner;
class Root {
public static int numRoot(int n, int sum){
while (n != 0) {
sum = sum + n % 10;
n = n / 10;
}
return sum;
}
public static void main(String[] args){
int sum = 0;
Scanner in = new Scanner(System.in);
System.out.print("Enter a number here");
int n = in.nextInt();
int root = numRoot(int sum, int n);
System.out.print("the sum of the digits off given num is " + root);
}
}
You have error here, Correct it.
int root = numRoot(int sum, int n); // this is wrong
Change it to
int root = numRoot(n,sum); // should use correct order of input parameters
This should be your method, you do not need to pass sum:
public static int numRoot(int n){
int sum=0;
while (n != 0) {
sum += n % 10;
n = n / 10;
}
return sum;
}
and you shall call it like this:
int root = numRoot(n);

Categories