The Programming Project

Thursday, October 16, 2014

Digit fifth powers :Problem 30 : Project Euler

Digit fifth powers :Problem 30 : Project Euler

Surprisingly there are only three numbers that can be written as the sum of fourth powers of their digits:
1634 = 14 + 64 + 34 + 44
8208 = 84 + 24 + 04 + 84
9474 = 94 + 44 + 74 + 44
As 1 = 14 is not a sum it is not included.
The sum of these numbers is 1634 + 8208 + 9474 = 19316.
Find the sum of all the numbers that can be written as the sum of fifth powers of their digits.

To get hold of the upper limit see

Digit factorials : Problem 34 : Project Euler



Python Code

 def digitFifthPowers():
    number = 10
    sumNumbers = 0
    digitfifthsum = 0
    while number < 7*9**5+1:
        strnumber = str(number)  
        digitfifthsum = 0
        for i in range(len(strnumber)):
            digitfifthsum = digitfifthsum + int(strnumber[i])**5
            if digitfifthsum > number:
                break
        if digitfifthsum == number:
            sumNumbers = sumNumbers + number
            print number,"Sum of the digits raised 5 is equal to the number itself"
        number = number + 1
    print "Required Sum is",sumNumbers          
digitFifthPowers()      

Digit factorials : Problem 34 : Project Euler

Digit factorials : Problem 34 Project Euler

145 is a curious number, as 1! + 4! + 5! = 1 + 24 + 120 = 145.
Find the sum of all numbers which are equal to the sum of the factorial of their digits.
Note: as 1! = 1 and 2! = 2 are not sums they are not included.

To find the upper limit for this problem observe that for a n-digit number the maximum possible  Digit Factorial Sum is 9!*n

For n = 7, Max. Digit Factorial Sum is 9!*7 =2,540,160 which is a 7 digit number
For n = 8, Max. Digit Factorial Sum is 9!*8 =2,903,040 which is a 7 digit number. Hence a the Digit Factorial Sum can never be equal to a 8 digit number! 

Python Code

def digitFactorials():
    def fact(digit):
        l=1
        for i in range(digit):
            l=l*digit
            digit=digit-1
        return l
    number = 10
    sumNumbers = 0
    digitfactsum = 0
    while number < 2540161:
        strnumber = str(number)   
        digitfactsum = 0
        for i in range(len(strnumber)):
            digitfactsum = digitfactsum + fact(int(strnumber[i]))
            if digitfactsum > number:
                break
        if digitfactsum == number:
            sumNumbers = sumNumbers + number
            print number,"Sum of the digits factorials is equal to the number itself"
        number = number + 1
    print "Required Sum is",sumNumbers           
digitFactorials()       

Distinct powers : Problem 29 : Project Euler : Python Code

Distinct powers : Problem 29 : Project Euler

Consider all integer combinations of ab for 2 ≤ a ≤ 5 and 2 ≤ b ≤ 5:
22=4, 23=8, 24=16, 25=32
32=9, 33=27, 34=81, 35=243
42=16, 43=64, 44=256, 45=1024
52=25, 53=125, 54=625, 55=3125
If they are then placed in numerical order, with any repeats removed, we get the following sequence of 15 distinct terms:
4, 8, 9, 16, 25, 27, 32, 64, 81, 125, 243, 256, 625, 1024, 3125
How many distinct terms are in the sequence generated by ab for 2 ≤ a ≤ 100 and 2 ≤ b ≤ 100

 Python Code


def distinctPowers():
    powerList = ()
    for a in range(2,101):
        for b in range(2,101):
            temp = a**b;
            if temp  in powerList:
                continue
            else:
                powerList = powerList + (temp,)
    print len(powerList)               
distinctPowers()       

Number letter counts : Problem 17 : JAVA CODE

Number letter counts : Problem 17 : Project Euler

 

If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.
If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used?

NOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two) contains 23 letters and 115 (one hundred and fifteen) contains 20 letters. The use of "and" when writing out numbers is in compliance with British usage.

JAVA CODE

import java.util.*;
public class NumberLetterCount {
    public static void main(String[] args) {
        ToWords numbObject = new ToWords();
        for(int i = 1; i <=1000; i++) {
            numbObject.toWord(i);
            }
        System.out.println("Letters used:"+numbObject.totalLetterCount());   
        }
    }
class ToWords {
    public void toWord(int numb) {
        this.number = numb;
        this.word = "";
        String temp = "";
        temp +=number;
        switch(temp.length()) {
            case 1:
                word = oneTwoDigit[number-1];
                           
            break;
           
            case 2:
                if ( number <= 20)
                    word = oneTwoDigit[number-1];
                   
                else {
                    if ( (temp.charAt(1)-48) == 0 )
                         word += tens[(temp.charAt(0)-48)-1];
                       
                    else    
                         word += tens[(temp.charAt(0)-48)-1]+ " "+oneTwoDigit[(temp.charAt(1)-48)-1];
                       
                    }
            break;
           
            case 3:
                if ( (temp.charAt(1)-48) == 0 && (temp.charAt(2)-48) == 0)
                    word += hundreds[(temp.charAt(0)-48)-1];
                   
                else if ( (temp.charAt(2)-48) == 0 )    
                    word += hundreds[(temp.charAt(0)-48)-1]+" and "+tens[(temp.charAt(1)-48)-1];
                   
                else {
                    if ( (temp.charAt(1)-48) == 0 )
                        word += hundreds[(temp.charAt(0)-48)-1]+" and "+oneTwoDigit[(temp.charAt(2)-48)-1];
                       
                    else   
                        if ( (temp.charAt(1)-48) == 1 )
                             word += hundreds[(temp.charAt(0)-48)-1]+" and "+oneTwoDigit[(temp.charAt(2)-48)-1+10];
                        else   
                            word += hundreds[(temp.charAt(0)-48)-1]+" and "+tens[(temp.charAt(1)-48)-1]+"-"+oneTwoDigit[(temp.charAt(2)-48)-1];   
                       
                    }
            break;
           
            case 4:
                word = "One Thousand";
               
            break;
            }   
        System.out.println(number+" in words: "+word);
        lettersCount(word);   
        }   
    private void lettersCount(String word) {   
        for( int i = 0; i < word.length(); i++ )
            if (word.charAt(i) == ' ' || word.charAt(i) == '-')
                continue;
            else
                letterCount +=1;   
        }
    public int totalLetterCount() {
        return letterCount;
        }   
    private String[] oneTwoDigit =  {"One","Two","Three","Four","Five","Six","Seven",
                    "Eight","Nine","Ten","Eleven","Twelve",
                    "Thirteen","Fourteen","Fifteen","Sixteen",
                    "Seventeen","Eighteen","Nineteen","Twenty"};   
                   
    private String[] tens =     {"Ten","Twenty","Thirty","Forty","Fifty","Sixty",
                     "Seventy","Eighty","Ninety"};
               
    private String[] hundreds =     {"One Hundred","Two Hundred","Three Hundred","Four Hundred","Five Hundred",
                         "Six Hundred","Seven Hundred","Eight Hundred","Nine Hundred"};               
    private int number;
    private int letterCount = 0;
    private String word;   
    }           

Wednesday, October 15, 2014

Goldbach's other conjecture : Problem 46 Pyhton Code

Goldbach's other conjecture : Problem 46

It was proposed by Christian Goldbach that every odd composite number can be written as the sum of a prime and twice a square.
9 = 7 + 2×12
15 = 7 + 2×22
21 = 3 + 2×32
25 = 7 + 2×32
27 = 19 + 2×22
33 = 31 + 2×12
It turns out that the conjecture was false.
What is the smallest odd composite that cannot be written as the sum of a prime and twice a square?

Problem Source :  Euler Project

Python Code

import math
def goldbachConjecture():
    found = False
    def checkPrime(numb):
        prime = True
        if numb == 1:
            return False
        for i in range(int(math.sqrt(numb))):
            i = i+2
            if numb%i == 0:
                prime = False
                break
        if numb == 2:
            return True
        else:           
            return prime
    def nextOddCompositeNumber(numb):
        numb = numb+1
        while checkPrime(numb) == True or numb %2 == 0:
            numb = numb+1
        return numb;           
    numb = 9    
    while found == False:
        k = 1
        goldtrue = False
        while numb-2*k**2 > 0 :
            if checkPrime(numb-2*k**2) == True:
                goldtrue = True
                break
            k = k+1   
        if goldtrue == True:
            found = False
            numb = nextOddCompositeNumber(numb)
        else:
            found = True
            print "smallest odd composite that cannot be written as the sum of a prime and twice a square",numb
goldbachConjecture()           

Friday, October 10, 2014

Insertion Sort : Python Code & Linked List implementation

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.
Sorting is typically done in-place, by iterating up the array, growing the sorted list behind it. At each array-position, it checks the value there against the largest value in the sorted list (which happens to be next to it, in the previous array-position checked). If larger, it leaves the element in place and moves to the next. If smaller, it finds the correct position within the sorted list, shifts all the larger values up to make a space, and inserts into that correct position.


Python Code

import random
def InsertionSort():
    N = input("Enter the number of elements in the list:")
    unsortedList = [0 for i in range(N)]
    for i in range(N):
        """ user input can be taken here"""
        unsortedList[i] = int(random.random()*N)
        i = i + 1
    print 'Unsorted list is:',unsortedList
    i = 0
    sortedList = [0 for i in range(N)]
    sortedList[0] = unsortedList[0]
    """ counter holds the number of elements inserted in the sorted list"""
    counter = 1
    for i in range (N-1):
        i = i + 1
        temp = counter
        while unsortedList[i] < sortedList[counter-1] and counter > 0:
            sortedList[counter] = sortedList[counter-1]
            counter = counter - 1
        sortedList[counter] = unsortedList[i]
        temp = temp+1
        counter = temp
    print 'Sorted list is:',sortedList           
InsertionSort()   

Wednesday, October 8, 2014

Binary Tree Traversal : C Code


Binary Tree Traversals inorder,preorder and postorder.  

#include<stdlib.h>
#include<stdio.h>
struct binaryTree {
   int key;
   struct binaryTree *right, *left;
};

typedef struct binaryTree node;

void insert(node **tree, int val);
void preorderTraversal(node *root);
void inorderTraversal(node *root);
void postorderTraversal(node *root);

int main() {
   node *root;
   int i,val,search;
   root = NULL;
   while(1) {
      printf("\n Enter the value (-1 to exit):");
      scanf("%d",&val);   
      if( val == -1)
          break;
      insert(&root, val);
   }
   printf("\n Pre-order Traversal:");
   preorderTraversal(root);
   printf("\n");
   printf("\n Inorder Traversal:");
   inorderTraversal(root);
   printf("\n");
   printf("\n Postorder Traversal:");
   postorderTraversal(root);
   printf("\n");
   return 0;
}
void postorderTraversal(node *root) {
    if (root != NULL) {
            postorderTraversal(root->left);
            postorderTraversal(root->right);
              printf("%d ",root->key);
                }
    }
void inorderTraversal(node *root) {
    if (root != NULL) {
            inorderTraversal(root->left);
              printf("%d ",root->key);
                inorderTraversal(root->right);
               }
    }
void preorderTraversal(node *root) {
    if (root != NULL)
        printf("%d ",root->key);
    if (root->left != NULL)
        preorderTraversal(root->left);   
    if (root->right != NULL)
        preorderTraversal(root->right);       
    }
void insert(node **tree, int val) {
   if((*tree) == NULL) {
      *tree = (node *)malloc(sizeof(node));
      (*tree)->key = val;
      (*tree)->right=(*tree)->left=NULL;
      return;
   }
   if(val < (*tree)->key)
      insert(&(*tree)->left, val);
   else if(val > (*tree)->key)
      insert(&(*tree)->right, val);
    }