# Blog Archives

## Project Euler Problem#14 solution in C++

## Longest Collatz sequence

The following iterative sequence is defined for the set of positive integers:

`n` `n`/2 (`n` is even)

`n` 3`n` + 1 (`n` is odd)

Using the rule above and starting with 13, we generate the following sequence:

It can be seen that this sequence (starting at 13 and finishing at 1) contains 10 terms. Although it has not been proved yet (Collatz Problem), it is thought that all starting numbers finish at 1.

Which starting number, under one million, produces the longest chain?

**NOTE:** Once the chain starts the terms are allowed to go above one million.

Solution:

#include <iostream> int main () { int N = 1000000; int CHECKPOINT = 800000; long long nTemp = N; int chainCount = 1; int check = 0; long long myNum = 0; for (int i = N; i > CHECKPOINT; --i) { while (nTemp != 1) { if ((nTemp%2) == 0) { nTemp = nTemp/2; }else { nTemp = (nTemp*3) + 1; } ++chainCount; } --N; nTemp = N; if (check < chainCount) { check = chainCount; myNum = nTemp; } chainCount = 1; } std::cout << "The number " << myNum << " has longest chain of " << check << std::endl; }

###### Related articles

- Longest Collatz Sequence (copingwithcomputers.com)
- Longest Collatz Sequence (copingwithcomputers.wordpress.com)
- Project Euler Problem#13 solution in C++ (alikhuram.wordpress.com)
- Project Euler Problem#12 solution in C++ (alikhuram.wordpress.com)

## Project Euler Problem#12 solution in C++

The sequence of triangle numbers is generated by adding the natural numbers. So the 7^{th} triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:

1, 3, 6, 10, 15, 21, 28, 36, 45, 55, …

Let us list the factors of the first seven triangle numbers:

1: 1

3: 1,3

6: 1,2,3,6

10: 1,2,5,10

15: 1,3,5,15

21: 1,3,7,21

28: 1,2,4,7,14,28

We can see that 28 is the first triangle number to have over five divisors.

What is the value of the first triangle number to have over five hundred divisors?

**Solution:**

#include <cstdio> #include <cmath> int numDivisors(int num) { int divisors = 1, exp; //handle 2 and 3 as special case exp = 0; while (num % 2 == 0) { num /= 2; exp++; } divisors *= (exp+1); exp = 0; while (num % 3 == 0) { num /= 3; exp++; } divisors *= (exp+1); //the other primes are 6k +/- 1 int i = 5; int root = floor(sqrt(num)); while (i <= root) { exp = 0; while (num % i == 0) { num /= i; exp++; } divisors *= (exp+1); if (i % 6 == 1) i += 4; else i += 2; root = floor(sqrt(num)); } //a single largest prime factor if (num != 1) divisors *= 2; return divisors; } int main(void) { int n = 0; int divisors = 0; while (divisors <= 500) { //while (n <= 10) { n++; //since t = n*(n+1)/2 and gcd(n,n+1)=1 if (n % 2 == 0) divisors = numDivisors(n/2) * numDivisors(n+1); else divisors = numDivisors(n) * numDivisors((n+1)/2); } printf("%d - %ld: %d\n", n, (long)n*(n+1)/2, divisors); }

###### Related articles

- Project Euler Problem#10 solution in C++ (alikhuram.wordpress.com)
- Project Euler problem#9 solution in C++ (alikhuram.wordpress.com)
- What is Pascal’s Triangle?, Part 2 (scientificamerican.com)

## Project Euler Problem#10 solution in C++

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

**Explanation:**

In mathematics, the **sieve of Eratosthenes** (Greek: κόσκινον Ἐρατοσθένους), one of a number of prime number sieves, is a simple, ancient algorithm for finding all prime numbers up to any given limit. It does so by iteratively marking as composite (i.e. not prime) the multiples of each prime, starting with the multiples of 2.^{[1]}

The multiples of a given prime are generated starting from that prime, as a sequence of numbers with the same difference, equal to that prime, between consecutive numbers.^{[1]} This is the sieve’s key distinction from using trial division to sequentially test each candidate number for divisibility by each prime.^{[2]}

The sieve of Eratosthenes is one of the most efficient ways to find all of the smaller primes (below 10 million or so).^{[3]} It is named after Eratosthenes of Cyrene, a Greek mathematician; although none of his works have survived, the sieve was described and attributed to Eratosthenes in the *Introduction to Arithmetic* by Nicomachus.^{[4]}

(above explanation taken from Wikipedia)

C++ solution:

*//solution is written in a flexible manner that you could compute sum of n prime numbers.*

#include <iostream>

using namespace std;

int find_prime (long *numArray, int maxNum)

{

long factor = 2; // we will make 2 as the starting point.

numArray[1] = 0; // rule out 1 from our logic to avoid incorrect results.

// loop condition will check, if we are in our maximum number limit.

//maxNum is the number till there we can find the prime numbers.

while ((factor * factor) < maxNum)

{

for (int i = 2; i < maxNum; i++) // we start our itration from number 2 not from 0 or 1 to get correct results.

{

if (numArray[i] != 0) //if a number on current array index is not zero, it is a prime or we havne’t yet checked it.

{

// we are putting zeros on all multiples of prime numbers, one by one.

if (numArray[i] != factor && (numArray[i]% factor) == 0)

{

numArray[i] = 0;

}

}

}

++factor;

}// after the loop, array will have zeros on all non prime locations and prime numbers.

}

int main ()

{

int prime_count = 0;

int64_t sum = 0;

int maxNum = 0;

int i = 0;

cout << “enter max number for array: “; // you need to test some upper limit values.

cin >> maxNum;

long *myArray = new long [maxNum];

//we fill up the array till the number we want to find the smallest positive number that is evenly divisible.

for (int i = 0; i < maxNum; i++)

{

myArray[i]= i;

}

// we will get prime numbers till the maxNum by calling below funtions.

find_prime(myArray, maxNum);

for (int j = 0; j< maxNum; j++)

{

sum += myArray[j];

}

cout << “Sum of first ” << maxNum << ” prime numbers : ” << sum << endl;

}

###### Related articles

- Project Euler Problem#7 solution in C++ (Brute Force) (alikhuram.wordpress.com)
- Implementing the Sieve of Eratosthenes with Functional Programming (raganwald.com)
- Simple prime sieve in C (houstin.wordpress.com)
- Prime numbers (haskell.org)
- Quadratic Sieve (programmingpraxis.com)
- Project Euler problem#9 solution in C++ (alikhuram.wordpress.com)
- New prime-generating algorithm (cp4space.wordpress.com)