public class Amstrong {
public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
String a = String.valueOf(i);
int b = a.charAt(0);
int c = a.charAt(1);
int d = a.charAt(2);
int e = b * b * b + c * c * c + d * d * d;
if (e == i) {
System.out.println(i);
}
}
}
}
//Help me out please, no error occurred but the result returned in the blank
You are not converting the characters to digits correctly.
One of the possible ways to fix it:
int b = a.charAt(0)-'0';
int c = a.charAt(1)-'0';
int d = a.charAt(2)-'0';
Another way:
int b = Character.digit (a.charAt(0),10);
int c = Character.digit (a.charAt(1),10);
int d = Character.digit (a.charAt(2),10);
Either way will give your the output:
153
370
371
407
Another way you can do it is:
import java.util.*;
public class ArmstrongNumber3
{
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter any number");
int n = sc.nextInt();
int b = n;
int sum = 0;
int d = 0;
while (n != 0) {
d = n % 10;
sum += (d * d * d);
n = n / 10;
}
if (sum == b) {
System.out.println("Armstrong");
} else
{
System.out.println("Not Armstrong");
}
}
}
import java.util.Scanner;
public class Amstrong {
public static void main(String args[]) {
Integer num, temp, len = 0, initVal;
double finalVal = 0;
Scanner scn = new Scanner(System.in);
System.out.println("Enter the number");
num = scn.nextInt();
initVal = num;
temp = num;
while (temp != 0) {
temp = temp / 10;
len++;
}
for (int i = 0; i <= len; i++) {
temp = num % 10;
finalVal = finalVal + Math.pow(temp, len);
num = num / 10;
}
if (Double.valueOf(initVal) == finalVal) {
System.out.println("Amstrong");
} else {
System.out.println("Not Amstrong");
}
}
}
Related
I have written a solution for Cyclic shift question on Hackerearth.
You can find this question on Hackerearth -> Codemonk -> Arrays & String -> Cyclic shift.
This solution gives TLE for large testcases. How do i optimize this code.
It seems like Java does not handle strings efficiently. Same code in Python gets accepted.
import java.io.*;
import java.util.*;
class TestClass
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0){
int N; int K;
N = sc.nextInt();
K = sc.nextInt();
String input = sc.next();
String B = "";
String inter = input;
int d = 0;
int period = -1;
for(int i = 0; i < N;i++){
if (B.compareTo(inter) < 0){
B = inter;
d = i;
}else if (B.compareTo(inter) == 0){
period = i - d;
break;
}
inter = inter.substring(1, inter.length()) + inter.substring(0, 1);
}
if(period == -1){
System.out.println(d + (K - 1L ) * N);
}else{
System.out.println(d + ((K - 1L) * period));
}
}
}
}
I tried fast IO, it did not help.
Please give me the Optimized Solution.
As suggested by maraca. Following solution does gets accepted.
import java.io.*;
import java.util.*;
class TestClass
{
static int compare(LinkedList<Character> A, LinkedList<Character> B){
Iterator<Character> i = A.iterator();
Iterator<Character> j = B.iterator();
if(A.size() == 0){ return -1;}
while (i.hasNext()) { // we know they have same length
char c = i.next();
char d = j.next();
if (c < d)
return -1;
else if (c > d)
return 1;
}
return 0;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0){
int N; int K;
N = sc.nextInt();
K = sc.nextInt();
String input = sc.next();
LinkedList<Character> B = new LinkedList<>();
int d = 0;
int period = -1;
LinkedList<Character> inter = new LinkedList<>();
for(char c: input.toCharArray()){inter.add(c);}
for(int i = 0; i < N;i++){
if (compare(B, inter) < 0){
B = new LinkedList<>(inter);
d = i;
}else if (compare(B, inter) == 0){
period = i - d;
break;
}
inter.add(inter.removeFirst());
}
if(period == -1){
System.out.println(d + (K - 1L ) * N);
}else{
System.out.println(d + ((K - 1L) * period));
}
}
}
}
Strings are immutable in Java. You could try to use LinkedList:
LinkdedList<Character> inter = new LinkedList<>(Arrays.stream(inter)
.boxed()
.collect(Collectors.toList()));
Alternatively:
LinkdedList<Character> inter = new LinkedList<>();
for (char c : input.toCharArray())
inter.add(c);
Then the shift becomes:
inter.add(inter.removeFirst());
And the comparison can be done as follows:
private int compare(List<Character> a, List<Character> b) {
Iterator<Character> i = a.iterator();
Iterator<Character> j = b.iterator();
while (i.hasNext()) { // we know they have same length
char c = i.next();
char d = j.next();
if (c < d)
return -1;
else if (c > d)
return 1;
}
return 0;
}
my solution
import java.io.*;
import java.util.*;
class TestClass
{
static int compare(LinkedList<Character> A, LinkedList<Character> B){
Iterator<Character> i = A.iterator();
Iterator<Character> j = B.iterator();
if(A.size() == 0){ return -1;}
while (i.hasNext()) { // we know they have same length
char c = i.next();
char d = j.next();
if (c < d)
return -1;
else if (c > d)
return 1;
}
return 0;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
while(T-- > 0){
int N; int K;
N = sc.nextInt();
K = sc.nextInt();
String input = sc.next();
LinkedList<Character> B = new LinkedList<>();
int d = 0;
int period = -1;
LinkedList<Character> inter = new LinkedList<>();
for(char c: input.toCharArray()){inter.add(c);}
for(int i = 0; i < N;i++){
if (compare(B, inter) < 0){
B = new LinkedList<>(inter);
d = i;
}else if (compare(B, inter) == 0){
period = i - d;
break;
}
inter.add(inter.removeFirst());
}
if(period == -1){
System.out.println(d + (K - 1L ) * N);
}else{
System.out.println(d + ((K - 1L) * period));
}
}
}
}
Ex: n1=100, n2=250, out=233.
Here I have to find the largest odd fibonacci number in the given set of ranges. If an odd fibonacci number doesn't exist then it should return 0. I am getting output as 50 times 0's and then 10 times 233. Where is my mistake and how can I get the desired output?
public class Fibo {
public static void main(String[] args) {
try {
int n1 = 100;
int n2 = 250;
int res = 0;
if (n1 % 2 == 0) {
n1 += 1;
for (int i = n1; i < n2; i += 2) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
System.out.println(res);
}
}
} catch(Exception ignored) {
System.out.println("0");
}
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public class Fibonacci {
public static void main(String[] args) {
System.out.println("Enter the starting range");
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
System.out.println("Enter the ending range");
int r = sc.nextInt();
int res = 0;
for (int i = n; i <= r; i++) {
if (isPerfectSquare(5 * i * i + 4) || isPerfectSquare(5 * i * i - 4))
res = i;
}
System.out.println("The biggest odd number in the range is"+" "+res);
}
public static boolean isPerfectSquare(int num) {
double sqrt = Math.sqrt(num);
int x = (int)sqrt;
return Math.pow(sqrt, 2) == Math.pow(x, 2);
}
}
public static int getLargestOddFibonacciBetween(int lo, int hi) {
assert lo <= hi;
int f0 = 0;
int f1 = 1;
int res = -1;
while (f1 <= hi) {
int val = f0 + f1;
f0 = f1;
f1 = val;
if (val >= lo && val <= hi && isOdd(val))
res = val;
}
return res;
}
private static boolean isOdd(int val) {
return (val & 1) == 1;
}
I am new in java and I have got assigment with armstrong numbers.
I am already created new class ArmstrongNumber.java where I initialized method from this website: http://www.programmingsimplified.com/java/source-code/java-program-armstrong-number
Now in a class where is main method I created another method where I am calling ArmstrongNumber class and now I have to return armstrong number from interval from [100 till 999].
There is where I am stuck now .
public static void armtrongNumbs()
{
ArmstrongNumber returnObj = new ArmstrongNumber(); // here i m calling class.
int start = 100;
int end = 999;
for(int i = start; i<= end; i++)
{
number = i + number;
returnObj.Armstrong(number);
}
//returnObj.Armstrong();
}
How could my loop return only armstrong numbers?
Edit: ArmstrongNumber class
class ArmstrongNumber
{
public void Armstrong(int number)
{
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
System.out.println(n + " is an Armstrong number.");
else
System.out.println(n + " is not an Armstrong number.");
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p*n;
return p;
}
}
Based on your requirement, you need logic of ArmstrongNumber.java and mold it to suit as per your requirements.
You just need to use the following code and can stop worrying about using ArmstrongNumber.java
package hello;
public class Abc {
public static void main(String[] args) {
int n, sum, temp, remainder, digits;
int start = 100;
int end = 999;
for (int i = start; i <= end; i++) {
sum = 0;
digits = 0;
temp = i;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp / 10;
}
temp = i;
while (temp != 0) {
remainder = temp % 10;
sum = sum + power(remainder, digits);
temp = temp / 10;
}
if (i == sum)
System.out.println(i + " is an Armstrong number.");
}
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
Here you can see, how the sum and digits are initialised to zero for every number and then the rest of logic is same. You can verify that 153, 370, 371, 407 are printed as Armstrong numbers.
Hope this helps
try like
public int[] Armstrong(int start ,int end){
int a[],i=0;
for(int i = start; i<= end; i++)
{
number = i + number;
int n, sum = 0, temp, remainder, digits = 0;
Scanner in = new Scanner(System.in);
System.out.println("Input a number to check if it is an Armstrong number");
n = in.nextInt();
temp = n;
// Count number of digits
while (temp != 0) {
digits++;
temp = temp/10;
}
temp = n;
while (temp != 0) {
remainder = temp%10;
sum = sum + power(remainder, digits);
temp = temp/10;
}
if (n == sum)
a[i++]=n;
else
System.out.println(n + " is not an Armstrong number.");
}
return a;
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
I've got a problem with some simple code. I haven't seen where is the problem in my code. It returns false when it should return true, since 153 is an Armstrong Number.
Following is my code:
public class Armstrong {
static double nArms, unidad, decena, centena, aux;
Armstrong(){
}
Armstrong(double nArms){
this.nArms = nArms;
}
public boolean esArmstrong(double nArms){
aux = nArms % 100;
centena = nArms / 100;
decena = aux / 10;
unidad = aux % 10;
this.nArms = Math.pow(unidad, 3) + Math.pow(decena, 3) +Math.pow(centena, 3);
if(this.nArms == nArms){
return true;
}else{
return false;
}
}
public static void main(String[] args) {
Armstrong arms = new Armstrong();
System.out.println(arms.esArmstrong(153));
}
}
You are using double when you intend to do integer arithmetic. For example, when you write
centena = nArms / 100;
you are doing floating point division, (and centena is assigned the value 1.53) but you want to perform integer division. Use int, long (or BigInteger) instead.
As others already mentioned never use Double for Integer calculation
Now If I were you I would have optimized my code to this
int check=0;
int n=num; // num is user-input number
while(n>0)//suppose n =153
{
int rem=n%10;
check=check+(int)Math.pow(rem,3);
n=n/10;
}
if(check==num)
System.out.println(num+" is Armstrong");
/*First time while loop runs rem = 3 and n= 15
So check = 0+3*3*3=27
Second time while loop runs rem = 5 and n= 1
So check = 27+5*5*5 = 152
Again n =1 so rem = 1 and check = 152+1*1*1 = 153
This time the thw while fails the exits
ultimately check == num so it is armstrong */
import java.util.Scanner;
public class Armstrong {
public static void main(String args[]) {
System.out.println("Input number of digit to find out Armstrong");
Scanner sc = new Scanner(System.in);
int r = sc.nextInt();
String s[] = new String[r];
System.out.println("Please enter digits");
StringBuilder sb = new StringBuilder(r);
for (int i = 0; i < r; i++) {
String userInput = sc.next();
s[i] = userInput;
sb.append(s[i]);
}
int e = Integer.parseInt(sb.toString()); //this is the Integer value entered to check Armstrong number
int d;
int k[] = new int[r];
for (int j = 0; j < r; j++) {
d = Integer.parseInt(s[j]);
k[j] = d * d * d * d* d* d;
}
int m[] = new int[r + 1];
int n[] = new int[r];
for (int l = 1; l <= r; l++) {
n[l - 1] = m[l - 1] + k[l - 1];
m[l] = n[l - 1];
}
if (e == m[r]) {
System.out.println("Entered number is Armstrong number");
} else {
System.out.println("Entered number is not an Armstrong number");
}
}
public void isArmstrong(String n)
{
char[] s=n.toCharArray();
int sum=0;
for(char num:s)
{
int i=Integer.parseInt(Character.toString(num));
int cube=i*i*i;
sum +=cube;
}
if(sum==Integer.parseInt(n))
{
System.out.println("Its an Armstrong Number");
}
else
{
System.out.println("Its not an Armstrong Number");
}
}
import java.util.*;
public class Main
{
public static void check_armstrong(int n)
{
/*Function to check whether a number is an armstrong number or not
Print true if yes else false */
int sum=0;
int temp=n;
while(n>0){
int remainder=n%10;
sum+=remainder*remainder*remainder;
n=n/10;
}
if(temp==sum){
System.out.println(true);
}else
System.out.println(false);
/* Do not change the code beyond this point*/
}
public static void main(String[]args)
{
Scanner sc=new Scanner(System.in);
int n =sc.nextInt();
check_armstrong(n);
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
int a, c, d, e = 0, temp = 0;
a = sc.nextInt();
c = a;
int z = a;
while (c > 0) {
c = c / 10;
temp++;
}
System.out.println("//");
int temp2 = temp;
while (temp2 > 0) {
int temp1 = 1;
d = a % 10;
for (int i = 0; i < temp; i++) {
temp1 = temp1 * d;
}
e = e + temp1;
a = a / 10;
temp2--;
}
if (z == e) {
System.out.println("number is armstrong");
} else {
System.out.println("number is not armstrong");
}
}
A positive number n is consecutive-factored if and only if it has factors, i and j where i > 1, j > 1 and j = i +1. I need a function that returns 1 if its argument is consecutive-factored, otherwise it returns 0.For example, 24=2*3*4 and 3 = 2+1 so it has the function has to return 1 in this case.
I have tried this:
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number %i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a =al(0);
int b = al(1);
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}
Can anyone help me with this problem?
First check if its even, then try trial division
if(n%2!=0) return 0;
for(i=2;i<sqrt(n);++i) {
int div=i*(i+1);
if( n % div ==0) { return 1; }
}
return 0;
very inefficient, but fine for small numbers. Beyond that try a factorisation algorithm from http://en.wikipedia.org/wiki/Prime_factorization.
I have solved my problem with the above code. Following is the code.
public class ConsecutiveFactor {
public static void main(String[] args) {
// TODO code application logic here
Scanner myscan = new Scanner(System.in);
System.out.print("Please enter a number: ");
int num = myscan.nextInt();
int res = isConsecutiveFactored(num);
System.out.println("Result: " + res);
}
static int isConsecutiveFactored(int number) {
ArrayList al = new ArrayList();
for (int i = 2; i <= number; i++) {
int j = 0;
int temp;
temp = number % i;
if (temp != 0) {
continue;
}
else {
al.add(i);
number = number / i;
j++;
}
}
Object ia[] = al.toArray();
System.out.println("Factors are: " + al);
int LengthOfList = al.size();
if (LengthOfList >= 2) {
int a = ((Integer) ia[0]).intValue();
int b = ((Integer) ia[1]).intValue();
if ((a + 1) == b) {
return 1;
} else {
return 0;
}
} else {
return 0;
}
}
}