-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathq20
More file actions
60 lines (59 loc) · 2 KB
/
Copy pathq20
File metadata and controls
60 lines (59 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
public int factorialSum(int num)
{
LinkedList<Integer> list = new LinkedList<Integer>();
list.add(1);
int retSum = 0;
for ( int i = 2; i <= num; i++ )
list = multiply(list, i);
for ( int i = 0; i < list.size(); i++ )
retSum += list.get(i);
for ( int i = list.size() - 1; i >= 0; i-- )
System.out.print(list.get(i));
System.out.println();
return retSum;
}
public LinkedList<Integer> multiply(LinkedList<Integer> list, int num)
{
LinkedList<Integer> ret = new LinkedList<Integer>(); // sum list
LinkedList<Integer> cur = new LinkedList<Integer>(); // temp list, for current multiplication result
// product is the result of product, carry is for any carry overs, tmp is for last digit of num when mod 10
// count is for number of digits, digit is for getting digit from ret list
int prod = 0, carry = 0, tmp = num, count = 0, digit = 0;
int i = 0;
while ( tmp != 0 )
{
for ( i = 0; i < list.size(); i++ )
{
// basic calculation of product and carry
prod = ( ( list.get(i) ) * ( tmp % 10 ) + carry ) % 10;
carry = ( ( list.get(i) ) * ( tmp % 10 ) + carry ) / 10;
cur.add(prod);
}
// if one loop further, add 0 to front. this is to match length (start) with return list
if ( count != 0 ) cur.push(0);
// this is to add the carry over digit to the end of cur list
if ( carry != 0 ) cur.add(carry);
carry = 0;
for ( i = 0; i < ret.size(); i++ )
{
digit = ret.get(i);
// the reason to use digit is to not mess up with carry, since the digit is updated in place
// so the updated carry will be different
ret.set(i, ( digit + cur.get(i) + carry ) % 10);
carry = ( digit + cur.get(i) + carry ) / 10;
}
// if same length, add to front
if ( i == cur.size() ) if ( carry != 0 ) ret.add(carry);
// not same length, add extra numbers to front
while ( i < cur.size() )
{
ret.add(( cur.get(i) + carry ) % 10);
carry = ( cur.get(i) + carry ) / 10;
i++;
}
count++;
tmp = tmp / 10;
cur.clear();
}
return ret;
}