Armstrong number in Java - java

This is my code, it is not producing any output. As I have started my loop from 100 so according to the logic used I should get answer as 153. But nothing is coming. Please help.
// Program to find the first Angstrom Number and display it!
public static void main(String[] args) {
int sum = 0;
int y, z;
System.out.println("Starting program");
for (int i = 100; i < 1000; i++) {
sum += (i % 10) * (i % 10) * (i % 10);
y = i / 10;
sum += (y % 10) * (y % 10) * (y % 10);
z = y / 10;
sum += z * z * z;
if (sum == i) {
System.out.println("The first Angstrom number is " + i);
break;
}
}
}

You should reset the sum in every step:
for (int i = 100; i < 1000; i++) {
sum = 0;
sum += (i%10) * (i%10) * (i%10);
....
}

You can find Armstrong number between two numbers by using this logic. Just change the values according to you need.
public class Armstrong {
public static void main(String[] args) {
int low = 999, high = 99999;
for(int number = low + 1; number < high; ++number) {
int digits = 0;
int result = 0;
int originalNumber = number;
// number of digits calculation
while (originalNumber != 0) {
originalNumber /= 10;
++digits;
}
originalNumber = number;
// result contains sum of nth power of its digits
while (originalNumber != 0) {
int remainder = originalNumber % 10;
result += Math.pow(remainder, digits);
originalNumber /= 10;
}
if (result == number)
System.out.print(number + " ");
}
}
}
Output of this program is:
1634 8208 9474 54748 92727 93084

public static int Power(int out,int res)
{
int count=res;
int temp=1;
while(count!=0)
{
temp=temp*out;
count--;
}
return temp;
}
public static int count1(int num)
{
int count=0;
while(num!=0)
{
num=num/10;
count++;
}
return count;
}
public static int isArmstrong(int num)
{
int out;
int sum=0;
int res=count1(num);
while(num!=0)
{
out=num%10;
sum=sum+Power(out,res);
num=num/10;
}
return sum;
}
public static void main(String[] args)
{
int start=10;
int end=100000;
for(int i=start;i<=end;i++)
{
int result=isArmstrong(i);
if(result==i)
{
System.out.println(i);
}

public class armstrongNumber
{
public void isArmstrong(String n)
{
char[] s=n.toCharArray();
int size=s.length;
int sum=0;
for(char num:s)
{int temp=1;
int i=Integer.parseInt(Character.toString(num));
for(int j=0;j<=size-1;j++)
{ temp *=i;}
sum +=temp;
}
if(sum==Integer.parseInt(n))
{
System.out.println(n+" is an Armstrong Number");
}
else
{
System.out.println(n+" is not an Armstrong Number");
}
}
public static void main(String[] args)
{
armstrongNumber am= new armstrongNumber();
am.isArmstrong("2");
am.isArmstrong("153");
am.isArmstrong("1634");
am.isArmstrong("231");
}
}

public class Armstrong {
public static int findArmStrong(int x, int y) {
if(x== getArmstrongSum(x)) return x;
else if(y== getArmstrongSum(y)) return y;
else return -1;
}
public static int getArmstrongSum(int num) {
int pow = String.valueOf(num).length();
return IntStream.iterate(num, i -> i / 10)
.limit(pow)
.map(i -> (int) Math.pow(i % 10, 3))
.sum();
}
public static void main(String[] args) {
System.out.println(findArmStrong(153, 154));
}
}

Related

fibonacci and prime numbers in one series

I am trying to do some mock questions of coding for an entrance exam, I came about this question and I am stuck at the PRIME NUMBERS part.
Here is the question:
Consider the below series: 1, 2, 1, 3, 2, 5, 3, 7, 5, 11, 8, 13, 13, 17, … This series is a mixture of 2 series – all the odd terms in this series form a Fibonacci series and all the even terms are the prime numbers in ascending order. Write a program to find the Nth term in this series. For example, when N = 14, the 14th term in the series is 17. So only the value 17 should be printed out.
public class OandF {
// main
public static void main(String[] args) {
System.out.println(dofibo(9));
}
public static int dofibo(int m) {
if(m == 0) {
return 0;
}
if(m == 1) {
return 1;
}
return dofibo(m-1) + dofibo(m-2);
}
}
// as you can see this is where I got to, and I don't know how to proceed
There are multiple ways to find the nth Prime number, the easiest way is to keep counting the prime numbers from 1 to n. But this is very time consuming otherwise refer to Fermat's theorems or Sieve of Eratosthenes.
private boolean isPrime(int n) {
if (n == 2 || n == 3) return true;
for(int i = 2; i < (int)Math.sqrt(n) + 1; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
public int nthPrime(int n) {
int number, primeCount;
for(number = 2, primeCount = 0; primeCount < n; number++) {
if (isPrime(number)) {
++primeCount;
}
}
return number;
}
You can try this, it may solve your problem.
class FibonacciExample1 {
public static void main(String args[]) {
int input = 20;
fibonacci(input);
System.out.print("-----------------------------");
prime(input);
}
public static void fibonacci(int input) {
int n1 = 0, n2 = 1, n3, i, count = input;
System.out.print(n1 + " " + n2);
for (i = 2; i < count; ++i) {
n3 = n1 + n2;
System.out.print(" " + n3);
n1 = n2;
n2 = n3;
}
}
public static void prime(int input) {
int i = 0;
int num = 0;
String primeNumbers = "";
for (i = 1; i <= input; i++) {
int counter = 0;
for (num = i; num >= 1; num--) {
if (i % num == 0) {
counter = counter + 1;
}
}
if (counter == 2) {
primeNumbers = primeNumbers + i + " ";
}
}
System.out.println(primeNumbers);
}
}
I'd make these two programs into simpler, infinite generators that are easier to debug and then sequence:
import java.util.ArrayList;
class Fibonacci {
int a = 0, b = 1;
int next() {
int c = a;
a = b;
b += c;
return a;
}
}
class Prime {
ArrayList<Integer> primes = new ArrayList<>();
int number = 2;
int next() {
if (number == 2) { // special case
primes.add(number);
number = 1;
return 2;
}
outer: while (true) {
number += 2;
for (int divisor: primes) {
if (divisor * divisor > number) {
break outer;
}
if (number % divisor == 0) {
break;
}
}
}
primes.add(number);
return number;
}
}
public class Example {
public static int sequence(int n) {
int nth = -1;
if ((n % 2) == 0) {
Fibonacci fibonacci_generator = new Fibonacci();
for (int i = 0; i < (n / 2) + 1; i++) {
nth = fibonacci_generator.next();
}
} else {
Prime prime_generator = new Prime();
for (int i = 0; i < (n + 1) / 2; i++) {
nth = prime_generator.next();
}
}
return nth;
}
public static void main(String args[]) {
System.out.println(sequence(13)); // 14th element counting from zero
}
}

write a program to add all the prime numbers from one to hundred

What is wrong in my code?
Expected output=1060
I checked with 1000 prime numbers sum. It will show correctly
output 3682913
public class PrimeNumber {
public static void main(String args[]){
int number = 2;
int count = 0;
long sum = 0;
while(count <100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for(int i=2; i<=number/2; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
You are counting up to 100 primes but not up to 100 numbers.
So your while loop should run up to 100 numbers.
This should be your main method:
int number = 2;
int count = 0;
long sum = 0;
while(number <= 100){
if(isPrimeNumber(number)){
sum += number;
count++;
}
number++;
}
System.out.println(sum);
}
This would give your output 1060.
Currently, you are counting the first 100 primes, not the primes found in the range 1 - 100. You can lose the count variable entirely here.
Your code can be simplifed as such, using a for loop instead to go from 2 to 100 (1 not included, of course)...
public class PrimeNumber {
public static void main(String args[]) {
long sum = 0;
for (int number = 2; number <= 100; number++) {
if (isPrimeNumber(number)) {
sum += number;
}
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
for (int i = 2; i <= number / 2; i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
}
You can use the below given code to find the sum of first prime numbers between 1 to 100. It will give you correct output.
public class PrimeNumber {
public static void main(String args[]){
int number = 2;
int sum = 0;
while(number <= 100){
if(isPrimeNumber(number)){
sum += number;
}
number++;
}
System.out.println(sum);
}
private static boolean isPrimeNumber(int number){
int sqrt = (int) Math.floor(Math.sqrt(number));
for(int i = 2; i <= sqrt; i++){
if(number % i == 0){
return false;
}
}
return true;
}
}
import java.util.Scanner;
public class Trial{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
boolean flag = false;
int max = 1000001;
long[] a = new long[max];
a[0] = 2;
int i = 3,j=0;
long sum = 2;
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long sum1 = 0;
int n = in.nextInt();
if(n>=i){
while(i<=n){
for(int y=0;a[y]<=Math.sqrt(i);y++){
if(a[y]==0){
break;
}
else if (i%a[y]==0){
flag = true;
break;
}
}
if(!flag){
a[++j]=i;
sum+=i;
}
flag =false;
i+=2;
}
System.out.println(sum);
}
else{
for(int y=0;a[y]<=n&&a[y]!=0;y++){
sum1+=a[y];
}
System.out.println(sum1);
}
}
}
}
here i stored prime numbers in an array if there is any query for the numbers which are already present in the array first 'if' statement will handle it and simple the sum upto that no. will be printed.This will save a lot time to recalculate the prime numbers and find their sum.

Armstrong number checking in Java

I'm trying to write a class which checks if a number is an Armstrong number or not. I'm having trouble with the following block of code.
public boolean checkNum(long num) {
digits = (int) (Math.log10(num) + 1);
String number = String.valueOf(num);
numDigits = number.toCharArray();
for (int i = 0; i < numDigits.length; i++) {
digit = numDigits[i] * 1.0;
power = digits * 1.0;
sum = sum + (long) (Math.pow(digit, power));
}
if (sum == num) {
return true;
} else {
return false;
}
}
The casting doesn't seem to work, and checkNum returns false every time. Is this a correct method, and are there any better ways of doing this?
Try this, using only arithmetic operations and it works for non-negative integers with an arbitrary number of digits (as long as they fit into a long).
public boolean checkNum(long num) {
long n = num;
long sum = 0;
// find the number of digits
int power = (int) Math.floor(Math.log10(n == 0 ? 1 : n)) + 1;
while (n != 0) {
int digit = (int) n % 10;
sum += Math.pow(digit, power);
n /= 10;
}
return sum == num;
}
Alternatively (albeit less efficiently) you could transform the number into a string and iterate over each of the characters converting them into digits. Here's a fixed version of your intended solution, with comments on the key points:
public boolean checkNum(long num) {
String number = String.valueOf(num);
char[] numDigits = number.toCharArray();
long sum = 0;
// a simple way to obtain the number of digits
int power = numDigits.length;
for (int i = 0; i < numDigits.length; i++) {
// this is how we transform a character into a digit
int digit = Character.digit(numDigits[i], 10);
// we need to rise digit to the value of power
sum = sum + (long) Math.pow(digit, power);
}
if (sum == num) {
return true;
} else {
return false;
}
}
For example, use either implementation to verify that the following are Armstrong numbers:
checkNum(6)
=> true
checkNum(371)
=> true
checkNum(1634)
=> true
You can also use this simple logic
public class Armstrong {
public static void main(String[] args) {
int number = 371, originalNumber, remainder, result = 0;
originalNumber = number;
while (originalNumber != 0)
{
remainder = originalNumber % 10;
result += Math.pow(remainder, 3);
originalNumber /= 10;
}
if(result == number)
System.out.println(number + " is an Armstrong number.");
else
System.out.println(number + " is not an Armstrong number.");
}
}
Guess This will work:
boolean isArmstrong(int x){
int s=0;
int u=x;
while(x!=0)
{
int y=x%10;
s=s+(y*y*y);
x=x/10;
}
if(u==s)
return true;
else
return false;
}
How to Check Number is Armstrong or Not
public boolean isArmstrongNum(int input)
{
int sum=0,rem,temp;
temp=input;
while(input>0)
{
rem=input%10;
input=input/10;
sum=sum+(rem*rem*rem);
}
return sum==temp;
}
In Kotlin, you can use:
fun main() {
println("---------------------------------------")
val userInputValues = Scanner(System.`in`)
//* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function
println("* Kotlin Program to Display Armstrong Numbers Between Intervals Using Function\n")
println("Enter your number range")
println("Enter start number of your range \t ")
val startRange = userInputValues.nextInt()
println("Enter end number of your range \t ")
val endRange = userInputValues.nextInt()
println("\n\n------ Armstrong number between $startRange and $endRange ------ ")
for (number in startRange..endRange) {
var stringNumber : String = number.toString()
var numberArray = stringNumber.toCharArray()
var powerOfNumber:Int = numberArray.size;
var result = 0
for (digit in numberArray){
var intDigit:Int = digit.toString().toInt()
result += intDigit.toDouble().pow(powerOfNumber.toDouble()).toInt()
}
if(result == number){
println( "$number is Armstrong number")
}
}
println("---------------------------------------")
}
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.print("Enter the number: ");
int number=scanner.nextInt();
scanner.close();
int lastDigit=0;
int reverseNum=0;
int originalNumber=number;
while(originalNumber!=0) {
lastDigit=originalNumber%10;
reverseNum +=(lastDigit*lastDigit*lastDigit);
originalNumber /=10;
}
if(reverseNum==number) {
System.out.println("Number is Armstrong");
}
else {
System.out.println("Number is not Armstrong");
}
}
This image is testing image of this code in terminal.
The best way is using while loop.
Here is your Answer for finding 3 digits Armstrong numbers.
import java.util.Scanner;
class Main {
////////////////////////////////////////////
////////////////////////////////////////////
public static void main(String args[])
{
System.out.println("Hello world!");
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
int numc = num;
int rem = 0;
int cu = 0;
int val = 0;
while(num != 0){
rem = num%10;
cu = rem*rem*rem;
val += cu;
num /= 10;
}
if(val == numc){
System.out.println("Yes its a Armstrong number ");
}else{
System.out.println("No its not a Armstrong number ");
}
}
}
///////////////////////////////////////////
Here I have done a code to find armstrong number dynamically:
import java.util.Scanner;
public class Armstrong {
public static void main(String[] args) {
if(isArmstrongNumber(input())) {
System.out.println("armstrong number");
} else {
System.out.println("Not armstrong number");
}
}
private static int input() {
try(Scanner reader = new Scanner(System.in)) {
return reader.nextInt();
}
}
private static int digitCount(int num) {
int count = 0;
while(num > 0) {
num = num / 10;
count++;
}
System.out.println("No of digit : " + count);
return count;
}
private static int power(int num, int count) {
int sum = 0;
while(num > 0) {
int result = 1;
int r2 = num % 10;
num /= 10;
for(int digit = count; digit > 0; digit--) {
result *= r2;
}
sum += result;
}
System.out.println("Sum : " + sum);
return sum;
}
public static boolean isArmstrongNumber(int num) {
int count = digitCount(num);
int sum = power(num, count);
return sum == num;
}
}
Here is the result:
371
No of digit : 3
Sum : 371
armstrong number
Hope this code helps you better.

trying to find the sum of even fibonacci numbers to 4 million

I am trying to find the sum of the even Fibonacci numbers up untill 4 million.
I found the numbers but i can't get them add up... in the if(n % 2 ==0) loop
8
34
144
610
2584
10946
46368
196418
832040
3524578
public static void number2()
{
int number = 40;
int a, b, c;
int numLim = 0;
a = 1;
b = 2;
while(numLim < 4000000)
{
c = a + b;
a = b;
b = c;
numLim = b;
if(numLim > 4000000)
{
break;
}
int sum = 0;
if(numLim % 2 == 0)
{
System.out.println(numLim);
sum = sum + numLim;
System.out.println("sum :" +sum);
}
}
}
You must define sum outside the while loop, or it will become 0 each iteration.
int sum = 0;
...
while ...
Remember not to set sum to 0 each iteration.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 32; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
sum += fibonacci;
System.out.println("This is the sum " +sum);
}
}
}
So I solved it like this, it's a little more efficient and the math works but Euler hates me, hope this helps.
public class Euler2 {
public static void main(String[] args) {
int fibonacci;
int num = 0;
int num2 = 1;
int loop;
int sum = 0;
System.out.println(num2);
for (loop = 0; loop <= 31; loop++) {
fibonacci = num + num2;
num = num2;
num2 = fibonacci;
System.out.println("Fibonacci number : " + fibonacci);
if (fibonacci%2 == 0) {
sum += fibonacci;
System.out.println(sum);
}
}
}
Sorry, this code works.
Tried doing the above in Java and here is my solution that works
public static void main(String[] args) {
int first = 1;
int second = 2;
int sum = 0;
int sumOfEvenValuedTerms = second;
for (int i = 0; i < 30; i++) {
sum = first + second;
if (sum <= 4000000) {
if (sum % 2 == 0) {
sumOfEvenValuedTerms += sum;
}
first = second;
second = sum;
}
}
System.out.println(sumOfEvenValuedTerms);
}
Output is 4613732
public static int getSumOfEvenNumbers(int n) {
int prev = 0;
int i =1;
int sum = 0;
while (i<n){
int nextNumber = i + prev;
if(nextNumber %2 ==0) {
System.out.println(nextNumber);
sum +=nextNumber;
}
prev = i;
i = nextNumber;
}
return sum;
}
public class evenFib {
public static void main(String[] args) {
double a = 1, b = 2, c = 0, sum = 0;
for (double i = 0; i <= 1000; i++) {
c = a + b;
a = b;
b = c;
if (c % 2 == 0 && sum < 4000000) {
sum = sum + c;
}
}
System.out.println(sum + 2);
}
}

How to write a recursive method to return the sum of digits in an int?

So this is my code so far.
public int getsum (int n){
int num = 23456;
int total = 0;
while (num != 0) {
total += num % 10;
num /= 10;
}
}
The problem is that i cant/know how to change this into a recursive method
Im kind of new with recursion and i need some help on implementing this method to change it so its recursive.
Short, recursive and does the job:
int getsum(int n) {
return n == 0 ? 0 : n % 10 + getsum(n/10);
}
Here it is,
//sumDigits function
int sumDigits(int n, int sum) {
// Basic Case to stop the recursion
if (n== 0) {
return sum;
} else {
sum = sum + n % 10; //recursive variable to keep the digits sum
n= n/10;
return sumDigits(n, sum); //returning sum to print it.
}
}
An example of the function in action:
public static void main(String[] args) {
int sum = sumDigits(121212, 0);
System.out.println(sum);
}
public int sumDigits(int n) {
return (n - 1) % 9 + 1;
}
public static int sumOfDigit(int num){
int sum=0;
if (num == 0)
return sum;
sum = num%10 + sumOfDigit(num/10);
return sum;
}
public static void main(String args[]) {
Scanner input=new Scanner(System.in);
System.out.print("Input num : ");
int num=input.nextInt();
int s=sumOfDigit(num);
System.out.println("Sum = "+s);
}
}
Try this:
int getSum(int num)
{
total = total + num % 10;
num = num/10;
if(num == 0)
{
return total;
} else {
return getSum(num);
}
}
int getSum(int N)
{
int totalN = 0;
totalN += (N% 10);
N/= 10;
if(N == 0)
return totalN;
else
return getSum(N) + totalN;
}
public static int digitSum (int n)
{
int r = n%10; //remainder, last digit of the number
int num = n/10; //the rest of the number without the last digit
if(num == 0)
{
return n;
} else {
return digitSum (num) + r;
}}
This works for positive numbers.
public int sumDigits(int n) {
int sum = 0;
if(n == 0){
return 0;
}
sum += n % 10; //add the sum
n /= 10; //keep cutting
return sum + sumDigits(n); //append sum to recursive call
}
import java.util.Scanner;
public class Adder {
public static void main(String[] args){
Scanner input = new Scanner(System.in);
System.out.print("Enter a number: ");
System.out.println();
int number = input.nextInt();
System.out.println("The sum of the digits is " +adder(number));
}
public static int adder(int num){
int length = String.valueOf(num).length();
int first , last , sum;
if (length==1){
return num;
}
else
{
first = num /10;
last = num % 10;
sum = last + adder(first);
}
return sum;
}
}
I see a lot of solutions on here, but not one in which seems as simple as what follows. I've tested it countless times and it works no problem:
public int sumDigits(int n) {
if (n == 0){
return 0;
}
else{
return n%10 + sumDigits(n/10);
}
}
I used recursion method in java for finding the sum of digits of a number
public class recursion_practice {
static int sum(int n) {
int sum = 0;
if (n > 0) {
int d = n % 10;
sum += d;
return sum + sum(n / 10);
} else return 0;
}
public static void main(String[] args) {
int x = 123;
System.out.println(sum(x)); // it will print 6 as 1+2+3=6
}
}
#include <iostream>
int useRecursion(int x);
using namespace std;
int main(){
int n;
cout<<"enter an integer: ";
cin>>n;
cout<<useRecursion(n)<<endl;
return 0;
}
int useRecursion(int x){
if(x/10 == 0)
return x;
else
return useRecursion(x/10) + useRecursion(x%10);
}
I think it's the shortest so far. The input thing is up too you, though.
public static int getSum(int input) { //example: input=246
int sum=0;
if (input%10==input) { //246%10=6;
return input%10; //2%10=2
}
return input%10+getSum((input-input%10)/10); //(246-6)/10=24; 24%10=4
}

Categories

Resources