# Thread: [SOLVED] for loop help!

1. Member
Join Date
Jan 2009
Posts
90
Rep Power
0

## [SOLVED] for loop help!

i wonder why that the highlighted part doesnt work for number 24?
it works fine when i enter 6.

Java Code:
```import java.util.Scanner;
public class sample{
public static void main (String[]args){

Scanner input = new Scanner(System.in);

System.out.println("Enter a positive integer number");
int num1 = input.nextInt();

System.out.println("Enter a positive integer number");
int num2 = input.nextInt();

int max = 1;
if (num1 >= num2){
max = num1;
}
else if (num1 <= num2){
max = num2;
}
System.out.println("The max is: "+ max);

//factorial
int total = 1;
if (max <=8){
for(int fac = max; fac >= 1; fac--){

total = total*fac;
}
System.out.println(max+"!"+ "is " + total);
}
[COLOR="Teal"]//check if max is factorial of any number

int total1 = 1;

for (int tri = 1; tri<max; tri++){
for (int fac1 = tri; fac1 >= 1; fac1--){
total1 = total1 * fac1;

if (total1 == max){

System.out.println(max+" is the factorial of "+ tri);
}
}

}[/COLOR]

int sum = 0;
//perfect number
for (int per = 1; per < max; per++){
if( max % per == 0){
sum = sum + per;
}
}
if (sum == max){

System.out.println( max + " is a perfect number");
}
else
System.out.println(max + " is not a perfect number");

}

}```

2. Senior Member
Join Date
Dec 2008
Location
Hong Kong
Posts
473
Rep Power
12
you need to initialize total1 to 1 at right position

and your algo is not correct enough...
you know .. 2! = 2, 1! = 1
Last edited by mtyoung; 02-07-2009 at 05:18 AM.

3. Member
Join Date
Jan 2009
Posts
90
Rep Power
0
Originally Posted by mtyoung
you need to initialize total1 to 1 at right position

and your algo is not correct enough...
you know .. 2! = 2, 1! = 1
ok i changed it and it works.
but i don't get why can't i initialize total1 at that position?

4. Senior Member
Join Date
Dec 2008
Location
Hong Kong
Posts
473
Rep Power
12
after you try to test max is 1!, then try to test for 2!, so on...
after trying 2!, total1 is 2, and you try to test for 3!,
total1 start from 2, not 1

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•