### Archive

Archive for April, 2015

## Project euler 27: Quadratic primes

Euler discovered the remarkable quadratic formula:

n² + n + 41

It turns out that the formula will produce 40 primes for the consecutive values n = 0 to 39. However, when n = 40, 402 + 40 + 41 = 40(40 + 1) + 41 is divisible by 41, and certainly when n = 41, 41² + 41 + 41 is clearly divisible by 41.

The incredible formula  n² − 79n + 1601 was discovered, which produces 80 primes for the consecutive values n = 0 to 79. The product of the coefficients, −79 and 1601, is −126479.

n² + an + b, where |a| < 1000 and |b| < 1000

where |n| is the modulus/absolute value of n
e.g. |11| = 11 and |−4| = 4

Find the product of the coefficients, a and b, for the quadratic expression that produces the maximum number of primes for consecutive values of n, starting with n = 0.

Solution:

It is self explanatory.

```#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

#define MAX 100000
vector <long> prime(0);

bool * seive_helper(bool primes[], int range)
{
for (int i = 3; i <= range / 2 ; ++i, ++i) {
for(int j =  i * 3; j <= range ; j += (i << 1)) {
primes[j] = true;
}
}
}

void  seive(int range)
{
int count = 0;
bool primes[MAX] = {false};
for(int i = 4; i <= range; ++i, ++i) {
primes[i] = true;
}
seive_helper(primes, range);
for(int i = 2; i <= range; ++i) {
if (!primes[i]) {
prime.push_back(i);
}
}
}

bool isPrime(long num, int range)
{
int i = 0;
while (i <= range) {
if (num == prime[i])
return true;
else if (num < prime[i])
return false;
i++;
}
return false;

}

int main()
{
long long sum = 0;
int max_count = 0;
int max_a;
int max_b;
seive(10000);
for (int i = -1000; i <= 1000; i++) {
for(int j = -1000; j <= 1000; j++) {
int n = 0;
int count = 0;
while(isPrime(n * n + i * n + j, 10000)) {
count++; n++;
}
if (count > max_count) {
max_count = count;
max_a = i;
max_b = j;
}
}
}
cout<<"max_a: "<<max_a<<endl;
cout<<"max_b: "<<max_b<<endl;
cout<<"max_count: "<<max_count<<endl;

return 0;
}

```

max_a: -61
max_b: 971
max_count: 71

real 0m1.584s
user 0m1.528s
sys 0m0.062s

Categories: Programming

## Project euler 26: Reciprocal cycles

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:

1/2 = 0.5
1/3 = 0.(3)
1/4 = 0.25
1/5 = 0.2
1/6 = 0.1(6)
1/7 = 0.(142857)
1/8 = 0.125
1/9 = 0.(1)
1/10 = 0.1
Where 0.1(6) means 0.166666…, and has a 1-digit recurring cycle. It can be seen that 1/7 has a 6-digit recurring cycle.

Find the value of d < 1000 for which 1/d contains the longest recurring cycle in its decimal fraction part.

Solution:

I solved this problem in a bruteforce manner. Divisor keeps incrementing from 2 to 1000.
We store the reminder instead of quotient in an array. When the same reminder repeats we know there is a recurring cycle. The maximum of that recurring cycle is the answer.

```#include <iostream>

#include <stdio.h>

using namespace std;
int max(int a, int b)
{
return (a > b) ? a: b;
}

int remArray[2000];
int divideByOne(long divisor)
{
int term = 0;
long mul = 1;
for(int i = 0; i < 2000; i++)
remArray[i] = 0;
while (mul != 0 && term < 2000) {
term++;
mul *= 10;
mul %= divisor;
if (remArray[mul] != 0)
break;
remArray[mul] = term;
}
return term;
}

int main()
{
int max_val = 0;
for(int i = 2; i <= 1000; i++)
max_val = max(max_val, divideByOne(i));
cout<<max_val;
return 0;
}

```

time ./a.exe
real 0m0.087s
user 0m0.030s
sys 0m0.046s

Categories: Programming

## project euler: Problem 25 1000-digit Fibonacci number

The Fibonacci sequence is defined by the recurrence relation:

Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.

Hence the first 12 terms will be:

F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144

The 12th term, F12, is the first term to contain three digits.

What is the first term in the Fibonacci sequence to contain 1000 digits?

Solution:
This problem is straight forward. A very simple python code as follows

```def func():
f1 = 1
f2 = 1
term = 2
while len(str(f2)) != 1000:
term += 1
f1, f2 = f2, f1 + f2
print term

func()
```

time python fibo.py

real 0m0.276s
user 0m0.125s
sys 0m0.109s

Categories: Programming

## Project euler: Problem 23 Non Abundant sums

A perfect number is a number for which the sum of its proper divisors is exactly equal to the number. For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28, which means that 28 is a perfect number.

A number n is called deficient if the sum of its proper divisors is less than n and it is called abundant if this sum exceeds n.

As 12 is the smallest abundant number, 1 + 2 + 3 + 4 + 6 = 16, the smallest number that can be written as the sum of two abundant numbers is 24. By mathematical analysis, it can be shown that all integers greater than 28123 can be written as the sum of two abundant numbers. However, this upper limit cannot be reduced any further by analysis even though it is known that the greatest number that cannot be expressed as the sum of two abundant numbers is less than this limit.

Find the sum of all the positive integers which cannot be written as the sum of two abundant numbers.

```#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <vector>
using namespace std;
#define MAX 28123

vector<long> abundant;

int allabundant(int num)
{
long sum = 0;
long p = 1;
for (long i = 2; i <= num; i++) {
sum = 1;
p = 2;
while (p * p <= i) {
if (i % p == 0) {
sum += p;
if (p != i / p)
sum += (i / p);
}
p++;
}
if (sum > i)
abundant.push_back(i);
}
}

int main()
{
long long sum = 0;
allabundant(MAX);
bool boolabund[MAX] = {false};
cout<< "Total number of abundant numbers below "<<MAX<<": "<<abundant.size()<<endl;
for(long i = 0; i < abundant.size(); i++) {
for(long j = i; j < abundant.size(); j++) {
long long temp = abundant[i] + abundant[j];
if (temp > MAX)
break;
boolabund[temp] = true;
}
}
for (int i = 0; i <= MAX; i++)
if (boolabund[i] == false)
sum += i;
}

```

time ./a.exe
Total number of abundant numbers below 28123: 6965

real 0m0.193s
user 0m0.124s
sys 0m0.046s

Categories: Programming

## Optimized solution for Project euler: Problem 21

In my previous post I’ve solved the problem 21 by caching the intermediate results. But it can be further optimized for calculating the sum of divisors as follows.

According to above method further optimized code is as follows

```#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

#define MAX 100000
vector <long> prime(0);

bool * seive_helper(bool primes[], int range)
{
for (int i = 3; i <= range / 2 ; ++i, ++i) {
for(int j =  i * 3; j <= range ; j += 2 * i) {
primes[j] = true;
}
}
}

void  seive(int range)
{
int count = 0;
bool primes[range + 1] = {false};
for(int i = 4; i <= range; ++i, ++i) {
primes[i] = true;
}
seive_helper(primes, range);
for(int i = 2; i <= range; ++i) {
if (!primes[i]) {
prime.push_back(i);
}
}
}
long long sumdivisors(long num)
{
long n = num;
long p = 2;
int i = 0;
int count = 0;
long sum = 1;
long lsum = 0;

while(n >= p * p && i < prime.size()) {
count = 0;
lsum = 1;
while (n % p == 0) {
n = n / p;
count++;
lsum *= p;
}
if (count > 0)
sum *= ((lsum * p) - 1) / (p - 1);
i++;
p = prime[i];
}
if (n > 1)
//Now cosider the only remaining prime which is greater than the sqrt of given number
sum *= (n + 1);
return sum - num;
}

long ami[100000] = {0};
int amicable(int num)
{
long sum = 0;

if (ami[num - 1] != 0)
return ami[num - 1];
else
{
ami[num - 1] = sumdivisors(num);
return ami[num - 1];
}

}

int main()
{
long long sum = 0;

seive((int)sqrt(10000));

for(int i = 2; i <= 10000; i++ ) {
if (amicable(i) != i && i == amicable(amicable(i))) {
sum += i;
}
}
cout<<"Sum of all amicable numbers: "<<sum;
return 0;
}
```

Time taken for the above solution is:
time ./a.exe
Sum of all amicable numbers: 31626
real 0m0.038s
user 0m0.000s
sys 0m0.030s

It is obviously better compared to my previous solution

Sum of all amicable numbers: 31626
real 0m0.185s
user 0m0.140s
sys 0m0.046s

Categories: Programming

## Project euler problem 22: Names scores

### Problem 22

Using names.txt (right click and ‘Save Link/Target As…’), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.

For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 × 53 = 49714.

What is the total of all the name scores in the file?

Solution:

Solution is for this problem is straight forward. I have used python for the ease of string operations.

```apyr=[]
def pyr():
with open("names.txt", "r")as out:
for i in out:
i=i.replace('\"','')
apyr = i.split(',')
apyr = sorted(apyr)
gsum = 0
for i in range(1, len(apyr) + 1):
lsum = 0
for j in range(0, len(apyr[i - 1])):
lsum += (ord(apyr[i - 1][j]) - 64)
gsum += lsum * i
print gsum

pyr()

```

Time taken for the solution is:

real 0m0.160s
user 0m0.030s
sys 0m0.140s

Categories: Programming

## Project euler problem 21: Amicable Number

Amicable Number:

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where ab, then a and b are an amicable pair and each of a and b are called amicable numbers.

For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.

Evaluate the sum of all the amicable numbers under 10000.

Solution:

This problem is also easy. Without any optimization it takes considerable amount of time. Hence, I solved it by caching the intermediate results into an array.

```#include <iostream>

#include <stdio.h>

using namespace std;
long ami[100000];
int amicable(int num)
{
long sum = 0;
if (ami[num - 1] != 0)
return ami[num - 1];
else
{
for (int i = 1; i <= num /2; i++)  {
if (num % i == 0)
sum += i;
}
ami[num - 1] = sum;
return sum;
}

}

int main()
{
long long sum = 0;

for(int i = 1; i <= 10000; i++ ) {
ami[i] = 0;
}
for(int i = 1; i <= 10000; i++ ) {
//        cout<<amicable(i)<<endl;
if (amicable(i) != i && i == amicable(amicable(i))) {
//          cout<<i<<endl;
sum += i;
}
}
cout<<"Sum of all amicable numbers: "<<sum;
return 0;
}

```

Time taken for the above implementation:

Sum of all amicable numbers: 31626
real 0m0.185s
user 0m0.140s
sys 0m0.046s

Categories: Programming, Technology