Project Euler – Problem # 5 – Solved with the Go programming language

What is the smallest number divisible by each of the numbers 1 to 20?

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

One Possible Solution: Go

package main

import (
	"fmt"
)

func evenlyDivisible(n int) (eD int) {
	/*Checks if number (n) is evenly divisible by the numbers 1 -20.*/

	counter := 0
	for i := 1; i < 21; i++ {
		if n%i == 0 {
			counter += 1
			if counter == 20 {
				return n
			}

		} else {
			return 1
		}
	}
	return 1
}
func main() {
	/*Main program - since we know that 2520 is evenly divisible by
	the first 10 integers, we know that the number in question is a
	multiple of 2520. So we start with 2520 and increment by that much
	until we find the smallest number that is evenly divisible by the
	first 20 integers (1-20)*/

	n := 2520
	Switch := 1
	for Switch >= 1 {
		smallest := evenlyDivisible(n)
		if smallest != 1 {
			fmt.Println(smallest)
			Switch = 0

		} else {
			n += 2520
		}
	}
}
Advertisements

Project Euler – Problem # 4 – Solved with the Go programming language

Find the largest palindrome made from the product of two 3-digit numbers.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 * 99.

Find the largest palindrome made from the product of two 3-digit numbers.

One Possible Solution: Go

package main

import "fmt"
import "strconv"
import "strings"

func isPalindrome(product int) (isP bool) {
	s := strconv.Itoa(product)
	a := strings.Split(s, "")
	L := len(a)
	for i := 0; i < L/2; i++ {
		a[i], a[L-i-1] = a[L-i-1], a[i]
	}
	x := strings.Join(a, "")
	y, _ := strconv.Atoi(x)
	if product == y {
		return true
	}
	return false

}

func main() {
	largest := 0
	for i := 1; i < 1000; i++ {
		for j := 1; j < 1000; j++ {
			product := i * j
			if isPalindrome(product) {
				if product > largest {
					largest = product
				}

			}
		}

	}
	fmt.Println(largest)
}

Project Euler – Problem # 3 – Solved with the Go programming language

Find the largest prime factor of a composite number.

The prime factors of 13195 are 5, 7, 13 and 29.

What is the largest prime factor of the number 600851475143 ?

One Possible Solution: Go

package main

import "fmt"
import "math"

func Sqrt(x float64) float64 {
	x = math.Sqrt(x)
	return x
}

func isPrime(n int) (isP bool) {
	k := int(Sqrt(float64(n)))
	for i := 2; i <= k; i++ {
		if n%i == 0 {
			return false
		}

	}
	return true

}

func getListOfPrimes(n int) (gLOP []int) {
	x := make([]int, n)
	x[0] = 2
	counter := 1
	for i := 3; i < n; i += 2 {
		if isPrime(i) {
			x[counter] = i
			counter += 1
		}
	}
	return x[:counter]

}

func main() {
	number := int64(600851475143)
	sN := int(Sqrt(float64(number)))
	s := int(Sqrt(float64(sN)))
	y := make([]int, s)
	x := getListOfPrimes(sN)
	counter := 0
	for i := 0; i < len(x); i++ {
		if int64(number)%int64(x[i]) == 0 {
			y[counter] = x[i]
			counter += 1
		}

	}
	fmt.Println(y[:counter])
}

Project Euler – Problem # 7 – Solved with Java & Python

Find the 10001st prime.

By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.

What is the 10 001st prime number?

One Possible Solution: Java


public class Problem_07 {
	public static void main(String args[])
	{
		Problem_07 prob_07Obj = new Problem_07();
		int Switch = 1;
		int counter = 1;
		int primes = 0;
		while(Switch == 1){
			if (prob_07Obj.isPrime(counter)){
				primes += 1;
				counter += 2;
			} else
			{
				counter += 2;
			}
			if (primes == 10001){
				System.out.println(counter - 2);
				Switch = 0;
			}
		}
		
	}
	public boolean isPrime(int n)
    {
    int k = (int) Math.sqrt(n);
            for (int i = 2; i <= k; i++)
            {
                    if (n % i == 0)
                            return false;
            }
            return true;
    }
}

One Possible Solution: Python

# Python version 2.7.2
# Platform = win32

def isprime(n):
    """Checks number (n) for primality, and returns
    True of False."""
    n = abs(int(n))
    if n < 2:
        return False
    if n == 2:
        return True
    if not n & 1:
        return False
    for x in range(3, int(n ** 0.5) + 1, 2):
        if n % x == 0:
            return False
    return True 

def main():
    """this example takes the numbers 1, 3, 5, 7, 9, etc., and
    checks for primality."""
    Switch = 1
    number = 1
    primes = 1 # start with 1 since we do not count 2, which is a prime
    while Switch == 1:
        if isprime(number):
            primes += 1 
        if primes == 10001: # Stop at 10001, and print that number
            print number
            Switch = 0
        number += 2

if __name__ == '__main__':
    main()

Project Euler – Problem # 6 – Solved with Java & Python

What is the difference between the sum of the squares and the square of the sums?

The sum of the squares of the first ten natural numbers is,

12 + 22 + … + 102 = 385

The square of the sum of the first ten natural numbers is,

(1 + 2 + … + 10)2 = 552 = 3025

Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 – 385 = 2640.

Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.

One Possible Solution: Java


public class Problem_06 {
	public static void main(String args[]){
		int sum_of_squares = 0;
		int square_of_sum = 0;
		int Sum = 0;
		for(int i = 1; i < 101; i++){
			int square = (int)Math.pow(i, 2);
			sum_of_squares += square;
			Sum += i;
		}
		square_of_sum = (int)Math.pow(Sum, 2);
		int Difference = square_of_sum - sum_of_squares;
		System.out.println("sum_of_squares = " + sum_of_squares);
		System.out.println("square_of_sum = " + square_of_sum);
		System.out.println("Difference is = " + Difference);
	}

}

One Possible Solution: Python

# Python version: 2.7.2
# Platform = win32

def main():
    """Finds the difference between the sum of the
    squares of the first one hundred natural numbers
    and the square of the sum."""
    sum_of_squares = 0
    square_of_sum = 0
    Sum = 0
    for i in range(1, 101):
        square = i ** 2
        sum_of_squares += square
        Sum += i
    square_of_sum = Sum ** 2
    print "sum_of_squares = ", sum_of_squares
    print "square_of_sum = ", square_of_sum
    Difference = square_of_sum - sum_of_squares
    print "Difference = ", Difference

if __name__ == '__main__':
    main()

“Coca-Cola”

When I purchased this puzzle at Wal-mart, the clerk said: “That looks like it will give you a headache.” Well, it did not give me a headache, but it was fairly challenging.

"Coca-Cola" - Photomosaic, 1000 piece

Can anyone identify this bird?

Can anyone identify this bird? I was out walking this morning along the Poudre River trail and came across a few black, long beaked, long legged, birds wading in some water. They were about the size of a duck and seemed to be feeding on insects in the water. It sure was fun to watch them elegantly strut around and simultaneously stretch out their neck to poke at a bit of food.

A black, long legged, long beaked, wading bird feeding in shallow water.

Project Euler – Problem # 5 – Solved with Java & Python

What is the smallest number divisible by each of the numbers 1 to 20?

2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.

What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20?

**********

“””Main program – since we know that 2520 is evenly divisible by
the first 10 integers, we know that the number in question is a
multiple of 2520. So we start with 2520 and increment by that much
until we find the smallest number that is evenly divisible by the
first 20 integers (1-20)”””

One Possible Solution: Java


public class Problem_5 {
	public static void main(String args[]){
		Problem_5 prob_5Obj = new Problem_5();
		int n = 2520;
		int Switch = 1;
		while (Switch == 1){
			Integer smallest = prob_5Obj.evenlyDivisible(n);
			if(smallest != 1){
				System.out.println(smallest);
				Switch = 0;
			}else{
				n += 2520;
			}
		}
	}
	
	public Integer evenlyDivisible(int n)
	{
		int counter = 0;
		for (int i = 1; i < 21; i++)
		{
			if(n % i == 0)
			{
				counter = counter + 1;
				if (counter == 20){
					return n;
				}
				else{
					continue;
				}
			}
			else{
				return 1;
			}
		}
		return 1;
	}
}

One Possible Solution: Python

# Python Version = 2.7.2
# Platform = win32
# Run time =  0.442848859867

import time

def evenlyDivisible(n):
    """Checks if number (n) is evenly divisible by the numbers 1 -20."""
    counter = 0
    for i in range(1, 21):
        if n % i == 0:
            counter = counter + 1
            if counter == 20:
                return n
        else:
            return 1

def main():
    """Main program - since we know that 2520 is evenly divisible by
    the first 10 integers, we know that the number in question is a
    multiple of 2520. So we start with 2520 and increment by that much
    until we find the smallest number that is evenly divisible by the
    first 20 integers (1-20)"""
    start_time = time.clock()
    n = 2520
    switch = 1
    while switch == 1:
        smallest = evenlyDivisible(n)
        if smallest != 1:
            print smallest
            switch = 0
        else:
            n += 2520
    run_time = time.clock() - start_time
    print "Run time = ", run_time
    
if __name__ == '__main__':
    main()

Project Euler – Problem # 4 – Solved with Java & Python

Find the largest palindrome made from the product of two 3-digit numbers.

A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.

Find the largest palindrome made from the product of two 3-digit numbers.

**********

The way to reverse a sting in Python is a lot shorter than the way to do it in Java. y = x[::-1] as opposed to the reverse method in the Java program.

One Possible Solution: Java


public class Problem_4 {
	public static void main(String args[]){
		Problem_4 prob_4Obj = new Problem_4();
		int largest = 0;
		for (int i = 100; i < 1000; i++){
			for (int r = 100; r < 1000; r++){
				String x = Integer.toString(i * r);
				String y = prob_4Obj.reverse(x);
				int xx = Integer.parseInt((x));
				if (x.equals(y)) {
					if (xx > largest){
						largest = (xx);
					}
				}
					
				}
			}
	System.out.println(largest);	
	}
		
// http://www.vbforums.com/showthread.php?t=320907
	 public String reverse(String arg)
	 {
		String tmp = null;
		if (arg.length() == 1)
		{
			return arg;
		}
		
		else
		{
			String lastChar = arg.substring(arg.length() -1, arg.length());
			
			String remainingString = arg.substring(0, arg.length() -1);
	
			tmp = lastChar + reverse(remainingString);
			return tmp;
			
			
		}
	  }
// http://www.vbforums.com/showthread.php?t=320907
}

One Possible Solution: Python

# Python version = 2.7.2
# Platform = win32

def findLargest():
    largest = 0
    for i in range (100, 999):
        for r in range(100, 999):
            x = str(i * r)
            y = x[::-1]
            if x == y:
                x = int(x)
                if x > largest:
                    largest = (x)
    return largest

def main():
    print findLargest()
        
if __name__ == '__main__':
    main()

Project Euler – Problem # 2 – Solved with the Go programming language

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, …

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

One Possible Solution: Go

package main

import "fmt"

func fib(n int) int {
	thesum := 0
	a := 1
	b := 1
	for a < n {
		if a%2 == 0 {
			thesum = thesum + a
		}
		a, b = b, a+b

	}
	return thesum

}

func main() {
	fmt.Println(fib(4000000))
}