Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I'm a java learner and I have a task to do from a forum to learn more.
The challenge is receive a number and multiply it by it's own digit like:
input 999
output `9*9*9 = 729 then 7*2*9 =126 again 1*2*6 = 12 finally 1*2=2 until it hits only one single digit.
I got this issue which I ask a variable to add the multiplication of an array of length of 2 it returns me this
1------------------1
49-----------------2
final result 2450
And this is the code..
class Persist {
public static void persistence(long n) {
String number = String.valueOf((int)n);
char[] digits1 = number.toCharArray();
int value = 1;
for(int i = 0 ;i <= digits1.length -1;i++) {
System.out.println(value + "-----------------" + digits1[i]);
value = value* (int)digits1[i];
}
System.out.println((int)value);
}
public static void main(String [] args) {
persistence(12);
}
}
I can try to fix this but I'm interested to know whats wrong.Thank you all in advanced for the help and just by passing by.
You are using the ASCII values of the numbers (see https://en.wikipedia.org/wiki/ASCII) i.e. 1=49 and 2=50
49 * 50 = 2450
You can use the Character.getNumericValue to get the numerical value of the char instead, i.e.
class Persist {
public static void persistence(long n) {
String number = String.valueOf((int)n);
char[] digits1 = number.toCharArray();
int value = 1;
for(int i = 0 ;i <= digits1.length -1;i++) {
System.out.println(value + "-----------------" + digits1[i]);
value = value* Character.getNumericValue((int)digits1[i]);
}
System.out.println((int)value);
}
public static void main(String [] args) {
persistence(12);
}
It is easiest to understand if you look at the values with a debugger. During the actual calculation value = value * (int)digits1[i] you are not using the value of the digits but the ASCII value of the chars. This is 1->49 and 2->50 so you are calculating 49*50=2450.
Change the line to value = value* Character.getNumericValue(digits1[i]); and you get what you are looking for.
Here's how I would do this. I adjusted it so that a 0 value digit is converted to 1. You can comment that out (did this because any digit of 0 turns the answer into 0). This version will keep re-multiplying until it's down to one digit.
public class Persist {
public static void main(String [] args) {
int answer = persistence(234);
System.out.println(" length: " + String.valueOf(answer).length());
while ( String.valueOf(answer).length() > 1) {
answer = persistence(answer);
} }
static int persistence(int n) {
int value = 1;
String myStr = String.valueOf(n);
int myStrLen = myStr.length();
int[] finalIntAr = new int[myStrLen];
for (int v=0; v< myStrLen; v++) {
String subS= myStr.substring(v,v+1);
System.out.println("the char/int : " + subS);
Integer bigI = Integer.valueOf(subS);
if (bigI == 0) { bigI = 1; } // take this out if you want 0 to perform as 0
finalIntAr[v] = bigI.intValue();
}
for (int i = 0 ; i < myStrLen; i++) {
System.out.println(" ----- first= " + value + " multiplied by : " + finalIntAr[i]);
value = value * finalIntAr[i];
}
System.out.println("\n CURRENT FINAL VALUE *** : " + value);
return value;
} }
Output:
the char/int : 2
the char/int : 3
the char/int : 4
----- first= 1 multiplied by : 2
----- first= 2 multiplied by : 3
----- first= 6 multiplied by : 4
CURRENT FINAL VALUE *** : 24
length: 2
the char/int : 2
the char/int : 4
----- first= 1 multiplied by : 2
----- first= 2 multiplied by : 4
CURRENT FINAL VALUE *** : 8
Since nobody posted an answer using no strings or chars, I will. Technically not an answer to your question, though.
public static void persistence(long x)
{
long answer = 1;
while (x != 0) {
long onesDigit = x % 10;
answer *= onesDigit;
x /= 10;
}
System.out.println(answer);
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
How to print out the number of a specific digit along with the digit itself in form "nxw." n is the frequency of the number, w is the number itself.
So, for example, if the user's input was 1 1 1. The output would be 3x1.
If the user's input was 1 1 1 at the first line and 7 7 1 1 0 at the second line. The output would be 3x1.2x7.2x1.1x0. with no spaces.
Note:
loop ends with a dot.
numbers don't have to be in a specific order
user can input as many digits as they want.
So for example, Input can be 1 1 1 at the first line 7 7 1 1 0 at the second ... etc.
This is my code so far. But I know that it's not true.
import java.util.*;
public class LaufLaengenKodierung {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int freq = 0;
int oldNum = 0;
int num = 0;
boolean first = true;
while(sc.hasNextInt()) {
int i = sc.nextInt();
if(i == oldNum) {
freq++;
num = i;
} else if(i != oldNum) {
freq = 1;
oldNum = i;
num = i;
if(first) {
first = false;
num = i;
freq = 1;
}
}
}
System.out.print(freq + "x" + num + ".");
sc.close();
}
}
Existing code needs to be slightly refactored to print the frequency and integer value as soon as a sub-sequence of the same values ends.
static void printRLE(String input) {
Scanner sc = new Scanner(input);
int freq = 0;
int oldNum = 0;
boolean first = true;
while(sc.hasNextInt()) {
int i = sc.nextInt();
if (i != oldNum || first) {
if (first)
first = false;
else // integer value changed
System.out.printf("%dx%d.", freq, oldNum);
oldNum = i;
freq = 1;
} else {
freq++;
}
}
if (!first)
System.out.printf("%dx%d.%n", freq, oldNum);
else
System.out.println("No integer found"); // or print 0x0 if it's correct
sc.close();
}
Tests:
String[] tests = {
"",
"abc.",
"11 11 11",
"1 1 1\n7 7 1 1 0",
"0 0 0",
};
for (String test: tests) {
System.out.println("test=[" + test + "]");
printRLE(test);
System.out.println("--------");
}
Output:
test=[]
No integer found
--------
test=[abc.]
No integer found
--------
test=[11 11 11]
3x11.
--------
test=[1 1 1
7 7 1 1 0]
3x1.2x7.2x1.1x0.
--------
test=[0 0 0]
3x0.
--------
Update
If separate digits need to be counted only (not the integer numbers), e.g. input 11 11 11 should be converted to 6x1. instead of 3x11. as shown above, the method should be refactored to process the digits inside numbers:
static void printRLEDigits(String input) {
Scanner sc = new Scanner(input);
int freq = 0;
int oldNum = 0;
boolean first = true;
out: while(sc.hasNext()) {
String s = sc.next(); // getting "number" delimited with whitespaces
for (char c: s.toCharArray()) {
if (!Character.isDigit(c)) {
break out;
}
int i = c - '0';
if (i != oldNum || first) {
if (first)
first = false;
else // digit changed
System.out.printf("%dx%d.", freq, oldNum);
oldNum = i;
freq = 1;
} else {
freq++;
}
}
}
if (!first)
System.out.printf("%dx%d.%n", freq, oldNum);
else
System.out.println("No integer found");
sc.close();
}
Output for tests: "11 11 11", "112 223", "1 1 1\n7 7 1 1 0", "0 0 0":
test=[11 11 11]
6x1.
--------
test=[112 223]
2x1.3x2.1x3.
--------
test=[1 1 1
7 7 1 1 0]
3x1.2x7.2x1.1x0.
--------
test=[0 0 0]
3x0.
--------
Online demo of both methods printRLE and printRLEDigits
You have to save the count of each individual digit. You can do this by creating an int array of size 10, for the digits 0 to 9. Then it's a simple loop like
while(sc.hasNextInt()) {
int i = sc.nextInt();
countArray[i]++;
}
After that you check each element in the array and output the count of the digit, when it is bigger than 0. It can look like this:
for (int i=0; i<countArray.length; i++) {
if (countArray[i] > 0) {
System.out.printf("%dx%d.", countArray[i], i);
}
}
Keep in mind that you have to check if the number entered by the user is in the limit of 0 to 9, otherwise you run into ArrayIndexOutOfBoundsExceptions.
This is the problem I'm trying to solve. Given a number like 6928:
difference between 6 and 9 is 3
difference between 9 and 2 is 7
difference between 2 and 8 is 6
So, the reduced form is 376. Since this is not a two-digit number, we repeat the process:
difference between 3 and 7 is 4
difference between 7 and 6 is 1
The result is 41, which is a two digit number, and the solution!
This is an attempt using the recursion method, but I am looking to do it in a non-recursive way:
public static int twodigit(int value) {
while (value > 99)
value = reduce(value);
return value;
}
private static int reduce(int value) {
return (value<=9? 0:reduce(value/10)*10 + Math.abs(value/10%10-value%10));
}
You can use a couple of nested loops and some math to add and select digits.
public static void main(String[] args) {
System.out.println(reduce(6928));
}
public static long reduce(long v) {
while(v > 9) {
System.out.println(v);
long y = 0, factor = 1;
// go through each digit from the bottom and calc the diff.
while(v > 9) {
y += factor * Math.abs(v % 10 - v / 10 % 10);
v /= 10;
// each digit is worth 10x the last.
factor *= 10;
}
v = y;
}
return v;
}
prints
6928
376
41
3
A tad more simple iterative method would be to convert the number into a string and pass it to below method
private static String calculateTwoDigitNumber(String number) {
while (number.length() > 2) {
String tmpNumber = "";
for (int i = 1; i < number.length(); i++) {
tmpNumber += Math
.abs(Integer.parseInt(number.charAt(i - 1) + "") - Integer.parseInt(number.charAt(i) + ""));
}
number = tmpNumber;
}
return number;
}
You can use StringBuilder instead of String if your input string is huge
I have this problem in front of me and I can't figure out how to solve it.
It's about the series 0,1,1,2,5,29,866... (Every number besides the first two is the sum of the squares of the previous two numbers (2^2+5^2=29)).
In the first part I had to write an algorithm (Not a native speaker so I don't really know the terminology) that would receive a place in the series and return it's value (6 returned 29)
This is how I wrote it:
public static int mod(int n)
{
if (n==1)
return 0;
if (n==2)
return 1;
else
return (int)(Math.pow(mod(n-1), 2))+(int)(Math.pow(mod(n-2), 2));
}
However, now I need that the algorithm will receive a number and return the total sum up to it in the series (6- 29+5+2+1+1+0=38)
I have no idea how to do this, I am trying but I am really unable to understand recursion so far, even if I wrote something right, how can I check it to be sure? And how generally to reach the right algorithm?
Using any extra parameters is forbidden.
Thanks in advance!
We want:
mod(1) = 0
mod(2) = 0+1
mod(3) = 0+1+1
mod(4) = 0+1+1+2
mod(5) = 0+1+1+2+5
mod(6) = 0+1+1+2+5+29
and we know that each term is defined as something like:
2^2+5^2=29
So to work out mod(7) we need to add the next term in the sequence x to mod(6).
Now we can work out the term using mod:
x = term(5)^2 + term(6)^2
term(5) = mod(5) - mod(4)
term(6) = mod(6) - mod(5)
x = (mod(5)-mod(4))^2 + (mod(6)-mod(5))^2
So we can work out mod(7) by evaluating mod(4),mod(5),mod(6) and combining the results.
Of course, this is going to be incredibly inefficient unless you memoize the function!
Example Python code:
def f(n):
if n<=0:
return 0
if n==1:
return 1
a=f(n-1)
b=f(n-2)
c=f(n-3)
return a+(a-b)**2+(b-c)**2
for n in range(10):
print f(n)
prints:
0
1
2
4
9
38
904
751701
563697636866
317754178345850590849300
How about this? :)
class Main {
public static void main(String[] args) {
final int N = 6; // Your number here.
System.out.println(result(N));
}
private static long result(final int n) {
if (n == 0) {
return 0;
} else {
return element(n) + result(n - 1);
}
}
private static long element(final int n) {
if (n == 1) {
return 0L;
} else if (n == 2) {
return 1L;
} else {
return sqr(element(n - 2)) + sqr(element(n - 1));
}
}
private static long sqr(final long x) {
return x * x;
}
}
Here is the idea that separate function (element) is responsible for finding n-th element in the sequence, and result is responsible for summing them up. Most probably there is a more efficient solution though. However, there is only one parameter.
I can think of a way of doing this with the constraints in your comments but it's a total hack. You need one method to do two things: find the current value and add previous values. One option is to use negative numbers to flag one of those function:
int f(int n) {
if (n > 0)
return f(-n) + f(n-1);
else if (n > -2)
return 0;
else if (n == -2)
return 1;
else
return f(n+1)*f(n+1)+f(n+2)*f(n+2);
}
The first 8 numbers output (before overflow) are:
0
1
2
4
9
38
904
751701
I don't recommend this solution but it does meet your constraints of being a single recursive method with a single argument.
Here is my proposal.
We know that:
f(n) = 0; n < 2
f(n) = 1; 2 >= n <= 3
f(n) = f(n-1)^2 + f(n-2)^2; n>3
So:
f(0)= 0
f(1)= 0
f(2)= f(1) + f(0) = 1
f(3)= f(2) + f(1) = 1
f(4)= f(3) + f(2) = 2
f(5)= f(4) + f(3) = 5
and so on
According with this behaivor we must implement a recursive function to return:
Total = sum f(n); n= 0:k; where k>0
I read you can use a static method but not use more than one parameter into the function. So, i used a static variable with the static method, just for control the execution of loop:
class Dummy
{
public static void main (String[] args) throws InterruptedException {
int n=10;
for(int i=1; i<=n; i++)
{
System.out.println("--------------------------");
System.out.println("Total for n:" + i +" = " + Dummy.f(i));
}
}
private static int counter = 0;
public static long f(int n)
{
counter++;
if(counter == 1)
{
long total = 0;
while(n>=0)
{
total += f(n);
n--;
}
counter--;
return total;
}
long result = 0;
long n1=0,n2=0;
if(n >= 2 && n <=3)
result++; //Increase 1
else if(n>3)
{
n1 = f(n-1);
n2 = f(n-2);
result = n1*n1 + n2*n2;
}
counter--;
return result;
}
}
the output:
--------------------------
Total for n:1 = 0
--------------------------
Total for n:2 = 1
--------------------------
Total for n:3 = 2
--------------------------
Total for n:4 = 4
--------------------------
Total for n:5 = 9
--------------------------
Total for n:6 = 38
--------------------------
Total for n:7 = 904
--------------------------
Total for n:8 = 751701
--------------------------
Total for n:9 = 563697636866
--------------------------
Total for n:10 = 9011676203564263700
I hope it helps you.
UPDATE: Here is another version without a static method and has the same output:
class Dummy
{
public static void main (String[] args) throws InterruptedException {
Dummy app = new Dummy();
int n=10;
for(int i=1; i<=n; i++)
{
System.out.println("--------------------------");
System.out.println("Total for n:" + i +" = " + app.mod(i));
}
}
private static int counter = 0;
public long mod(int n)
{
Dummy.counter++;
if(counter == 1)
{
long total = 0;
while(n>=0)
{
total += mod(n);
n--;
}
Dummy.counter--;
return total;
}
long result = 0;
long n1=0,n2=0;
if(n >= 2 && n <=3)
result++; //Increase 1
else if(n>3)
{
n1 = mod(n-1);
n2 = mod(n-2);
result = n1*n1 + n2*n2;
}
Dummy.counter--;
return result;
}
}
Non-recursive|Memoized
You should not use recursion since it will not be good in performance.
Use memoization instead.
def FibonacciModified(n):
fib = [0]*n
fib[0],fib[1]=0,1
for idx in range(2,n):
fib[idx] = fib[idx-1]**2 + fib[idx-2]**2
return fib
if __name__ == '__main__':
fib = FibonacciModified(8)
for x in fib:
print x
Output:
0
1
1
2
5
29
866
750797
The above will calculate every number in the series once[not more than that].
While in recursion an element in the series will be calculated multiple times irrespective of the fact that the number was calculated before.
http://www.geeksforgeeks.org/program-for-nth-fibonacci-number/
I am working on a program that takes an integer and finds the number of combinations of consecutive sums that the integer has:
The number 13 can be expressed as a sum of consecutive positive
integers 6 + 7. Fourteen can be expressed as 2 + 3 + 4 + 5, also a sum
of consecutive positive integers. Some numbers can be expressed as a
sum of consecutive positive integers in more than one way. For
example, 25 is 12 + 13 and is also 3 + 4 + 5 + 6 + 7.
I researched and read that it's the number of odd factors minus one. So I wrote a program that finds the number of odd factors and my answer is still wrong in certain cases. Any insight?
Code seems to work fine but there is a crash due to Timeout which is probably due to optimization error.
The constraints for possible input size is
1 to 10^(12)
The code below is copied from alfasin's answer below:
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
static long consecutive(long num) {
while (num % 2 == 0) num /= 2;
return consecutiveHelper(num);
}
public static long consecutiveHelper(long num) {
return LongStream.rangeClosed(3, (num / 2)).parallel().filter(x -> x % 2 != 0).map(fn -> (num % fn == 0) ? 1 : 0).sum();
}
public static void main(String[] args) throws IOException {
Scanner in = new Scanner(System.in);
final String fileName = System.getenv("OUTPUT_PATH");
BufferedWriter bw = null;
if (fileName != null) {
bw = new BufferedWriter(new FileWriter(fileName));
}
else {
bw = new BufferedWriter(new OutputStreamWriter(System.out));
}
int res;
long num;
num = Long.parseLong(in.nextLine().trim());
res = consecutive(num);
bw.write(String.valueOf(res));
bw.newLine();
bw.close();
}
}
This is what i currently have
As the post i answered to was duplicate, I copied my answer here as well.Let's try to find a pseudo-optimized method to resolve your problem :
What you need to do is to decompose your number in prime factors.
For example, if you take 1200 :
1200 = 2*2*2*2*3*5*5 = 1 * 2^4 * 3^1 * 5^2
You can then analyze how you could get odd factors with those prime factors. A quick analyze will tell you that :
odd * odd = odd
odd * even = even
even * even = even
With that in mind, let's find all the factors we get with odd * odd :
1 * 1 = 1
3 * 1 = 3
5 * 1 = 5
5 * 3 = 15
5 * 5 = 25
5 * 5 * 3 = 75
A quick way to find these combinations without writing them all is the "plus 1 method" : add 1 to the number of occurences of each prime odd factor, and multiply them together :
We found that 1200 = 1 * 2^4 * 3^1 * 5^2, so we can do :
("number of 3" + 1) ("number of 5" + 1) = (1 + 1) ( 2 + 1) = 6
There are 6 odd factors for the number 1200, and as you stated, remove 1 from that number to get the number of combinations of consecutive sums that 1200 has :
6 - 1 = 5 <-- woohoo ! finally got the result !
Now, let's look at the code. What we want to have is a Map, the keys being the prime factors and the values being the number of their occurences :
/*
If number is odd,
find the number in the keys and add 1 to its value.
If the number is not in the keys, add it with value = 1.
*/
public static void addValue(Map<Integer, Integer> factors, int i) {
if(i % 2 != 0) {
int count = factors.containsKey(i) ? factors.get(i) : 0;
factors.put(i, ++count);
}
}
/*
Classic algorithm to find prime numbers
*/
public static Map<Integer, Integer> oddPrimeFactors(int number) {
int n = number;
Map<Integer, Integer> factors = new HashMap<>();
for (int i = 2; i <= n / i; i++) {
while (n % i == 0) {
addValue(factors, i);
n /= i;
}
}
if(n > 1) addValue(factors, n);
return factors;
}
With that, let's try to print what the map contains for number 1200 :
public static void main(String[] args) {
int n = 1200;
System.out.println(oddPrimeFactors(n));
}
$n : {3=1, 5=2}
Good ! Now let's finish the program with the method we developed before :
public static int combinations = 1;
public static void main(String[] args) {
int n = 1200;
oddPrimeFactors(n).forEach((key, value) -> combinations *= (value + 1));
combinations--;
System.out.println(combinations);
}
$combinations = 5
Finished ! feel free to ask if you did not understand something !
Note : I tried my program with the max value Integer can handle and it took less than one second for my program to proceed, which seems pretty fast to me. It could probably be faster though, it's up to you to find the most optimized version of this code !
Here are the optimizations that we discussed in the comments section, see comments as markers:
static int consecutive(long num) {
while (num % 2 == 0) num /= 2; // 1st opt.
return consecutiveHelper(num)-1;
}
public static int consecutiveHelper(long num) {
long factorNumber = 1;
int count = 0;
while(factorNumber <= num / 2) { // 2nd opt.
if(num % factorNumber == 0) {
count++;
}
factorNumber += 2; // 3rd opt.
}
if (num % 2 != 0) {
count++;
}
return count;
}
UPDATE
I managed to reduce ~50% runtime for big-numbers (10^12) by using Java 8 Stream interface and running in parallel:
static long consecutive(long num) {
while (num % 2 == 0) num /= 2;
return consecutiveHelper(num);
}
public static long consecutiveHelper(long num) {
return LongStream
.rangeClosed(3, (num / 2))
.parallel()
.filter(x -> x % 2 != 0)
.map(fn -> (num % fn == 0) ? 1 : 0)
.sum();
}
That said, parallel will be more expensive when you're dealing with smaller numbers. If you want your answer to be optimal you should use both methods: for smaller numbers use the first and for large numbers use the latter.
i want to print all armstrong number between 1 to 1000 in a textfield using awt or swing but i only get last value by my code .So pls help me
public void actionPerformed(ActionEvent e)
{
String s1=tf.getText();
int n1=Integer.parseInt(s1);
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
tf1.setText(String.valueOf(original[i]));
}
}
}
For those who don't know, an Armstrong number (or narcissistic number) is a number with n digits that is equal to the sum of each of its digits to the nth power.
(x1*10(n-1))+(x1*10(n-2))...+(x1*10(n-n)) = (x1)n+(x2)n...+(xn)n
This means that if the number is 1 digit, the power will be 1.
Therefore there are 10 1 digit numbers that are Armstrong numbers:
0 = 01
1 = 11
2 = 21
3 = 31
4 = 41
5 = 51
6 = 61
7 = 71
8 = 81
9 = 91
Your code, as written, will not identify any of those numbers as Armstrong numbers.
Your code will also incorrectly identify some numbers as 4 digit Armstrong numbers because you only look for the the cubes (3rd power) of your numbers not the 4th power.
(You don't have to worry about twos because there are no two digit Armstrong numbers)
In order to correctly determine all the possible Armstrong numbers between 1 and 10000, you need to write a "power" loop that finds the nth power of a number by multiplying the number n times.
This would look something like:
//... beginning of your original function
//added a string to hold all the values before printing
string holder = "";
for(int n=0;n<10000;n++){
int sum=0;
//n=original you had duplicate variables (just use n as original)
int number = n;
//while there are still digits left
while(number>0){
//get the smallest digit
int r=number%10;
//----------"Power" loop-----------
int foo = n;
//once smaller than 10, it's only a power of 1 (which is itself)
while(foo>=10){
//this means foo = foo/10
foo /= 10;
//this means r = r*r
r*=r;
}
//this means sum = sum+r
sum += r;
//you should have the hang of it by now
number/=10;
}
//if the sum equals the original number
if(sum==n){
//put that number into the end of a string (separated by newlines `\n`)
holder+=n+"\n";
}
}
//All done, so set the text box value
tf1.setText(holder);
//... whatever code you want to finish up
This should also take care of your problem with the textBox getting overwritten each time. By saving the numbers into a string and then printing all of them at once, only once (no overwriting), you'll get better results.
You always set the current found value. But you should set the previous found values + current found value.
tf1.setText(String.valueOf(original));
But more performant would be to use a stringbuilder object and append the result each time and set this value to the textfield outside the loop.
public void actionPerformed(ActionEvent e)
{
StringBuilder s = new StringBuilder ();
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
s.append(original + " ");
}
}
tf1.setText (stringBuilder.toString ());
}
Easy, all you do is change the setText() method of the TextField1 component with append().
It works! The remaining will do! Try it once.
public void actionPerformed(ActionEvent e)
{
String s1=tf.getText();
int n1=Integer.parseInt(s1);
for(int n=0;n<10000;n++)
{
int sum=0;
int number=n;
int original=number;
while(number>0)
{
int r=number%10;
sum+=r*r*r;
number=number/10;
}
if(sum==original)
{
tf1.append(String.valueOf(original[i] + " "));
}
}
}
Very simple program in C to list all armstrong number between 1 to 1000000.
#include<stdio.h>
#include<conio.h>
#include<math.h>
main()
{
long a = 1, c=0, b, e, f, d = 0,g=0,p,j,count=0;
printf("All armstron number between 1 and 1000000 is listed below!\n");
while (c <= 1000000)
{
j = c;
if (j >= 10)
{
while (j >= 10)
{
j = j / 10;
g++;
}
}
p = g + 1;
g = 0;
a = c;
f = a;
while (a >= 10)
{
b = a % 10;
d = d + pow(b,p);
a = a / 10;
}
e = pow(a,p) + d;
d = 0;
if (e == f)
{
count++;
printf("%ld\t",count );
printf("%ld\n", f);
}
c++;
}
getch();
}