#!/usr/bin/python
from sys import argv
from math import sqrt
def f(x):
s = 1
for i in xrange(2, int(sqrt(x))+1):
if x % i == 0:
s += i + x/i
return s == x
def ff(p):
if p <= 6:
return True
x = p-1
if x % 9 == 0:
x = x / 9
else:
return False
j = 0
while True:
t = 32*j**2 + 20*j + 3
j += 1
if t == x:
return True
elif t > x:
return False
def p(n):
t1 = 2
j = 0
while True:
t2 = t1
t1 = t1 << 1
p = (t1-1) * t2
if ff(p) and f(p):
j += 1
if j == n:
return p
if __name__ == '__main__':
if len(argv) <= 1:
print p(2)
else:
print p(int(argv[1]))
If you don't like Python, here's the C version (uses long long, which is technically avialable in C99 only, but gcc supports it as an extension anyway (for C89)):
#include
#include
#include
int f(long long n);
int ff(long long n);
int main(int argc, char *argv[])
{
long long j, n, p, t1=2, t2;
if (argc <= 1) {
n = 2;
} else {
n = strtol(argv[1], 0, 0);
}
for (j=0; j < n; ) {
t2 = t1;
t1 = t1 << 1;
p = (t1-1)*t2;
if (ff(p) && f(p)) {
++j;
}
}
printf("%lld\n", p);
return EXIT_SUCCESS;
}
int f(long long n)
{
long long int y = sqrt(n), s = 1, i;
for (i=2; i <= y; ++i) {
if (n%i == 0) {
s += i + n/i;
}
}
return s == n;
}
int ff(long long n)
{
long long i = n-1;
long long j = 0;
if (n <= 6) {
return 1;
}
if (i % 9 == 0) {
i /= 9;
} else {
return 0;
}
while(1) {
long long t = 32*j*j + 20*j + 3;
++j;
if (t == i) {
return 1;
} else if (t > i) {
return 0;
}
}
}