Armstrong number code in Java is not working right - java

I am completely new to Java and am writing code to check whether a number is an Armstrong number or not in the range 0 to 999.
Please tell me what is wrong. When run on command prompt, it repeatedly prints:
1 is the count
Code:
import java.util.*;
class Armstrong
{
public static void main (String[] args)
{
int sum = 0;
for (int i = 0; i < 1000; i++)
{
int n = i;
int count =0;
while(n > 0)
{
int mod = n % 10;
n = n / 10;
count++;
}
System.out.println(+count+ "is the count");
for (int j = 1; j < count; j++)
{
int val = i % 10;
i= i / 10;
sum = val * val * val + sum;
}
if (sum == i)
{
System.out.println( +i+ "is an Armstrong number");
}
}
}
}

An Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits.
For starters, you always raise the digits to the power of 3, so your calculation can only work for i between 100 and 999.
Second, you are changing i within your inner loop, so the comparison at the end if (sum==i) will fail, since sum should be compared to the original i.
Next, you don't reset sum to 0 in each iteration of i.
You also skip one of the digits.
This seems to work :
int sum = 0;
for (int i = 100; i < 1000; i++) { // start at 100
sum = 0; // clear the sum in each iteration
int n = i;
int count = 0;
while (n > 0) {
int mod = n % 10;
n = n / 10;
count++;
}
n = i;
for (int j = 0; j < count; j++) { // iterate over all the digits
int val = n % 10;
n = n / 10; // don't change i
sum = val * val * val + sum;
}
if (sum == i) {
System.out.println(i + " is an Armstrong number");
}
}
This returns :
153 is an Armstrong number
370 is an Armstrong number
371 is an Armstrong number
407 is an Armstrong number

There is no need to run three loops. You can do it simpler that way:
for(int i = 0; i < 1000; i++) {
int currNumber = i;
int sum = 0;
while(currNumber != 0)
{
int mod = currNumber % 10;
sum = sum + mod * mod * mod;
currNumber = currNumber / 10;
}
if (i == sum) {
System.out.println(i + " is an Armstrong number");
}
}

Print Armstrong number in java
public class CalculatArmstrong
{
public static void main(String[] args)
{
for(int i=0;i<=2000;i++)
{
int number=i;
int n=number;
int rem;
int arms=0;
while(number>0)
{
rem=number%10;
arms=arms+rem*rem*rem;
number=number/10;
}
if(n==arms)
{
System.out.println(n);
}
}
}
}

Related

How to sum all whole numbers from 0 to 1000

How to sum all whole numbers to 1000
package proba;
public class Proba {
public static void main(String[] args) {
int a = 1;
int whole = 0;
int n = 1000;
int m = 500;
while (a <= n) {
if (a % 2 == 0) {
whole += ;
}
a++;
System.out.println("Rezultat parnih je: " + whole);
}
}
}
For all numbers from 0 till 1000, for loop
int sum = 0;
for (int i = 0; i < 1000; i++) {
sum += i;
}
System.out.println(sum);
For all even numbers, use an if to see if they are even
if (i % 2 == 0) // remainder is 0, meaning even
sum += i;
Edit: To add even and subtract odd
int sumOfEven;
for (int i = 0; i < 1000; i++) {
if (i % 2 == 0) {
sumOfEven += i;
}
}
int sumOfOdd;
for (int i = 0; i < 500; i++) {
if (i % 2 != 0) {
sumOfOdd += i;
}
}
System.out.println(sumOfEven - sumOfOdd); // Math.absolute can also be done here for a non-negative value
Adding all numbers just to subtract later 250 of them is not efficient. Just filter the ones you don't want in the total sum
int sum = IntStream.rangeClosed(1, 1000)
.filter(i -> i >= 500 || i % 2 == 0)
.sum();
System.out.println(sum);

To find out Armstrong number in between numbers

Below is my code.
package com.ofss.java.examples;
import java.util.Scanner;
class ArmstrongNumber {
public static void main(String[] args) {
int c = 0, a;
int n1, n2;//Range in which armstrong number need to find
Scanner s = new Scanner(System.in);
System.out.println("Enter the first number");
n1 = s.nextInt();
System.out.println("Enter the second number");
n2 = s.nextInt();
for (int i = n1; i <= n2; ++i) {
while (i > 0) {
a = i % 10;
System.out.println(a);
i = i / 10;
System.out.println(i);
c = c + (a * a * a);
System.out.println(c);
}
if (i == c)
System.out.println(c + "armstrong number");
else
System.out.println(c + "Not armstrong number");
}
}
}
I am getting incorrect results after executing. Code runs for infinite number till you stops it. It must print number between 151-154 (153 as armstrong).
Also, it is incorrectly printing 153 as not Armstrong number.
Armstrong Number
...is a number that is the sum of its own digits each raised to the power of the number of digits.
You should not change i since this is also used in
for (int i = n1; i <= n2; ++i)
Or you will probably never exit that loop eiter since you expect i to be negative at the end of the first iteration. Hard to increment until it reach n2.
Use a different variable to keep track of i safely.
int j = i;
while(j > 0) ...
About Armstrong number:
Armstrong number is a number that is the sum of its own digits each raised to the power of the number of digits
You need to put each digit to the power of the length of the number (the number of digit).
153 = 1^3 + 5^3 + 3^3
1634 = 1^4 + 6^4 + 3^4 + 4^4
Here is the method for it :
public static boolean isArmstrongNumber(int number){
int power = Integer.toString(number).length(); //just to get the number of digit...
int tmp = number;
int digit , sum = 0;
while(tmp > 0){
digit = tmp % 10;
sum += Math.round(Math.pow(digit , power));
tmp /= 10;
}
return sum == number;
}
Using this check from 0 to 10.000 gives :
0
1
2
3
4
5
6
7
8
9
153
370
371
407
1634
8208
9474
Same as Wikipedia :
The sequence of base 10 narcissistic numbers starts: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, ...
Note that using a method remove the risk of forgetting to reset your variable like c in your case. Correcting this would give you a few more "correct" results (well the one with 3 digits)
You can also use less mathematics to read the number and use char[], remember that you need to substract '0' value to get the numeric value for a character :
public static boolean isArmstrongNumber(int number){
char[] digits = Integer.toString(number).toCharArray();
int power = digits.length;
int sum = 0;
for(char c : digits){
int digit = c - '0';
sum += Math.round(Math.pow(digit, power));
}
return sum == number;
}
There are two things.
you are updating i everytime as you have used it in while, so use different variable than i for this calculation.
int num = i;
c is used to compare sum of cube is same as number but you are not resetting it once the one iteration is over. so make c=0 inside for loop.
c = 0;
Also while printing you are using c, there should be i which is correct and real number.
Below is the working code you may try.
public static void main(String[] args)
{
int c = 0, a;
int n1, n2;//Range in which armstrong number need to find
Scanner s = new Scanner(System.in);
System.out.println("Enter the first number");
n1 = s.nextInt();
System.out.println("Enter the second number");
n2 = s.nextInt();
for (int i = n1; i <= n2; ++i)
{
int num = i;
while (num > 0)
{
a = num % 10;
num = num / 10;
c = c + (a * a * a);
}
if (i == c)
System.out.println(i + "armstrong number");
else
System.out.println(i + "Not armstrong number");
c = 0;
}
}
public class ArmstrongNumber {
private final int n1, n2;
public ArmstrongNumber(int n1, int n2) {
this.n1 = n1;
this.n2 = n2;
}
protected static boolean isArmstrong(int n) {
if(n < 0)
return false;
int remaining=n;
int sumCube=0;
while (remaining>0) {
int d = remaining % 10;
sumCube += cube(d);
remaining /= 10;
}
return n == sumCube;
}
private static int cube(int d) {
return d*d*d;
}
public Integer[] find() {
List<Integer> results = new ArrayList<>();
for (int i = n1; i <= n2; ++i)
{
if (isArmstrong(i))
results.add(i);
}
return results.toArray(new Integer[0]);
}
}
There are lot of things to improve in your code. One of the working logics as below:
for (int i = n1; i <= n2; ++i) {
int sum = 0, remainder = 0, digits = 0, temp = 0;
temp = i;
while (temp != 0) {
digits++;
temp = temp / 10;
}
temp = i;
while (temp != 0) {
remainder = temp % 10;
sum = sum + (int) Math.pow(remainder, digits);
temp = temp / 10;
}
if (i == sum)
System.out.println(i + " is an Armstrong number.");
else
System.out.println(i + " isn't an Armstrong number.");
}

Armstrong number logic error

Here I've code to print armstrong numbers until some particular range. But this programs doesnt prints all the numbers within the range. It just prints armstrong number within range of 1000. Whats wrong in this code?
public static void main(String[] args) {
long N, temp, sum = 0;
Scanner ip = new Scanner(System.in);
System.out.print("Enter the range: ");
N = ip.nextLong();
for (long i = 1; i < N; i++) {
temp = i;
while (temp > 0) {
long rem = temp % 10;
sum = sum + (rem * rem * rem);
temp = temp / 10;
}
if (sum == i) {
System.out.println(" " + i);
}
sum = 0;
}
ip.close();
}
when the input is 100000 it just prints
Enter the range: 100000
1
153
370
371
407
According to the definition of Armstrong numbers, each digit in the number is to be raised to n where is the number of digits in the number.
However your logic does not implement that. It only raises digits to the third power.
That's why your code fails.
Here you go, use this code:
for (long i = 1; i < N; i++) {
temp = i;
int n=Long.toString(i).length();
while (temp > 0) {
long rem = temp % 10;
sum = sum + (long) Math.pow(rem, n);
temp = temp / 10;
}
if (sum == i) {
System.out.println(" " + i);
}
sum = 0;
}
Ideone link here.

Why while() creates magic?

I was writing a program to find armstrong numbers from 100 to 999. If I give number as an input program works but if I check number using while loop it says that every number not an armstrong number. I can't understand why.
That is the code:
package armstrong;
//import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
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();
n = 100;
while (n <= 999) {
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 not an Armstrong number.");
else System.out.println("Armstrong number:" + n);
n++;
}
}
static int power(int n, int r) {
int c, p = 1;
for (c = 1; c <= r; c++)
p = p * n;
return p;
}
}
You should initialize digits, sum to zero in your loop like:
while (n <= 999) {
digits = 0;
sum = 0
...
}
Based on this page: http://www.cs.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/arms.html
You should set sum to back to zero inside the loop:
while(n <= 999) {
temp = n;
sum = 0;
...
}
and power method should be:
static int power(int n) {
return n * n * n;
}
Hope it helps.

Loops and Prime Numbers

Write a program that prompts the user for an integer and then prints out all prime numbers up to that integer. For example, when the user enters 20, the program should print
2 3 5 7 11 13 17 19
Recall that a number is a prime number if it is not divisible by any number except 1 and itself.
I am trying to write this program but I am having difficulties, can anyone show me how to write this code?
This is what I have written but it is completely wrong.
import java.util.Scanner;
public class PrimeNumbers
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
System.out.print("Enter Integers: ");
int x;
int n = in.nextInt();
for (int i = 2; i < n ; i++)
{
x = i;
if (n % i != 0 && i % x != 0)
{
System.out.println(i);
}
x--;
}
}
}
Computes the number of primes less than or equal to N using
the Sieve of Eratosthenes.
% java PrimeSieve 25
The number of primes <= 25 is 9
% java PrimeSieve 100
The number of primes <= 100 is 25
% java -Xmx100m PrimeSieve 100000000
The number of primes <= 100000000 is 5761455
% java PrimeSieve -Xmx1100m 1000000000
The number of primes <= 1000000000 is 50847534
The 110MB and 1100MB is the amount of memory you want to allocate
to the program. If your computer has less, make this number smaller,
but it may prevent you from solving the problem for very large
values of N.
class PrimeSieve {
public static void main(String[] args) {
int N = Integer.parseInt(args[0]);
// initially assume all integers are prime
boolean[] isPrime = new boolean[N + 1];
for (int i = 2; i <= N; i++) {
isPrime[i] = true;
}
// mark non-primes <= N using Sieve of Eratosthenes
for (int i = 2; i*i <= N; i++) {
// if i is prime, then mark multiples of i as nonprime
// suffices to consider mutiples i, i+1, ..., N/i
if (isPrime[i]) {
for (int j = i; i*j <= N; j++) {
isPrime[i*j] = false;
}
}
}
// count primes
int primes = 0;
for (int i = 2; i <= N; i++) {
if (isPrime[i]){ primes++; System.out.print(i+", ");}
}
System.out.println("\nThe number of primes <= " + N + " is " + primes);
}
}
Use this method to check if a given int is a prime.
public static boolean isPrime(int a)
{
if ( a == 2)
return true;
int midpoint = Math.round(a/2);
for(int i = 2; i < midpoint; i++)
{
if(a % i == 0)
return false;
}
return true;
}
Explanation:
Loop through all the numbers until midpoint and modulus until you encounter 0 or not. If you encounter 0 then return false because we know that it is not prime, if we encounter no zero then we return true because it is prime.
We loop until midpoint because there is no need to loop further.
You can implement it in your loop via
for (int i = 2; i < n ; i++)
{
if (isPrime(i))
{
System.out.println(i);
}
}

Categories