UpCount
-
- Posts: 2
- Joined: Wed Nov 05, 2008 9:16 pm
- Contact:
I turned the program into a for-loop starting with 1 and solved it with that perl-snippet
Code: Select all
my $depth;
my $cc = 1;
for ( $depth = 1; $depth <= 11589; $depth++ ) {
$cc = $cc + ($depth % 7) + (((($cc ^ $depth) % 4) == 0) ? 1 : 0);
}
print $cc, "\n";
I did it the hard way... figuring out a "simple" program that does the equivalent.
pseudo-code:
works for inputs 'n' greater than 7
No need for looping nor recursion... too bad he didn't put a really huge number into the depth.
pseudo-code:
Code: Select all
int extra = n%7;
int sum = (n/7)*23 + 2;
switch(extra)
{
case 0:
sum+=0;
break;
case 1:
sum+=1;
break;
case 2:
sum+=3;
break;
case 3:
sum+=6;
break;
case 4:
sum+=11;
break;
case 5:
sum+=17;
break;
case 6:
sum+=23;
break;
}
return sum;
No need for looping nor recursion... too bad he didn't put a really huge number into the depth.
I don't like java, so I translated the code to PHP:
Didn't take more than 1 minute to translate and run
Code: Select all
function calc($depth) {
if ($depth == 0) return 1;
$cc = calc($depth - 1);
return (double)$cc + ($depth % 7) + (((($cc ^ $depth) % 4) == 0) ? 1 : 0);
}
echo calc(11589);
my version was:
Code: Select all
<html>
<script language="javascript" type="text/javascript">
function mycalc() {
var plus = new Array(0,1,2,3,5,6,6);
sum = 2302;
j=0;
for (i=700;i<11590;i++) {
sum+=plus[j];
j++;
if (j==7) {j=0;}
document.writeln("<br/>",i,"->",sum);
}
}
</script>
<p><script language="javascript" type="text/javascript">mycalc()</script> </p>
</body>
</html>
Yup, did exactly the same thing. Good ol' PHP :Pfido2509 wrote:I don't like java, so I translated the code to PHP:Didn't take more than 1 minute to translate and run ;)Code: Select all
function calc($depth) { if ($depth == 0) return 1; $cc = calc($depth - 1); return (double)$cc + ($depth % 7) + (((($cc ^ $depth) % 4) == 0) ? 1 : 0); } echo calc(11589);
-
- Posts: 4
- Joined: Thu May 07, 2009 10:27 pm
The iterative Java function:
Code: Select all
private long calc(int depth) {
long result = 1;
for(int i=1; i<=depth; i++) {
result = result + (i % 7) + ((((result ^ i) % 4) == 0) ? 1 : 0);
}
return result;
}
I just avoided stack issues by using different values, i.e. instead of calc(11589) I ran calc(9000) and changed the code to (29574 was the result of calc(9000)):
This way I could stepwise increase the "boundary" until at last I had the result
Just wondering why so many people wanted to rewrite the recursive code instead of taking advantage of it.
Code: Select all
public class UpCount {
private long calc(int depth) {
if (depth == 9000) return 29574;
long cc = calc(depth - 1);
return cc + (depth % 7) + ((((cc ^ depth) % 4) == 0) ? 1 : 0);
}
public static void main(String[] args) {
UpCount uc = new UpCount();
System.out.println(uc.calc(11589));
}
}
Just wondering why so many people wanted to rewrite the recursive code instead of taking advantage of it.