The Programming Project

Sunday, August 24, 2014

Longest Collatz sequence: Python Code

The following iterative sequence is defined for the set of positive integers:
nn/2 (n is even)
n → 3n + 1 (n is odd)
Using the rule above and starting with 13, we generate the following sequence:
13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1
 
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?

Python Code:

def Collatz():
    lengthCollatz = 1
    count = 1
    numb = 0
    longestCnumb =1
    for i in range(1000000):
        count = 1
        numb = i+1
        while numb != 1:
            if numb%2 == 0:
                numb = numb/2
            else:
                numb = 3*numb+1
            count +=1
        if count > lengthCollatz:
                lengthCollatz = count;   
                longestCnumb = i+1;
    print "Longest length of Collatz Sequence is:",lengthCollatz,"and the number is",longestCnumb                 
Collatz()

Sunday, August 17, 2014

Circular Prime: Python Code : Problem 35

The number, 197, is called a circular prime because all rotations of the digits: 197, 971, and 719, are themselves prime.
Write a program to check entered number is a Circular prime or not.
First few Circular Primes are

2,3,5,7,11,13,17,31,37,71,73,79,97,113,131,197,199,311,337,373,719,
733,919,971,991,1193,1931,3119,3779,7793,7937,9311,9377,11939,
19391,19937,37199,39119,,71993,91193,93719,93911,99371,193939,199933,
319993,331999,391939,393919,919393,933199,939193,939391,993319,999331

FOR JAVA CODE CLICK HERE

Python  Code

def CircularPrime():
    numb = int(input("Enter the number:"))
    flagCircular = True
    def CheckPrime(numb):
        flag = True
        for i in range(numb//2):
            i = i+2
            if numb%i == 0:
                flag = False
                break
        if flag == True:
            return True
        else:
            return False
    for i in range(len(str(numb))):
        if CheckPrime(numb) == True:
            flagCircular = True
        else:
            flagCircular = False
            break
        stringNumb = str(numb)
        firstDigit = stringNumb[0]
        tmpNumb =""
        for j in range(len(str(numb))-1):
            tmpNumb    += stringNumb[j+1]
        tmpNumb += stringNumb[0]
        numb = int(tmpNumb)
    if flagCircular == True:
        print ("Entered number is a Circular Prime")
    else:
        print ("Entered number is not not Circular Prime")
CircularPrime()

Saturday, August 16, 2014

Champernowne's constant: JAVA & Python CODE Problem 40

An irrational decimal fraction is created by concatenating the positive integers:
0.12345678910111213141516171819202122232425262728293031323334353637383940...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, write a program in JAVA/C/C++/Python  to find the nth digit of the fractional part

Euler Project : Problem 40

Python Code

# Champernowne's constant
def Champernowne():
    nthDigit = input("Enter the term whose value has to be found:")
    counter =0;
    for i in range(nthDigit):
        i +=1
        numb =""
        numb +=str(i)
        counter +=len(numb)
        if counter >= nthDigit:
            counter -= len(numb)
            j = 0
            while counter != nthDigit:
                counter +=1
                j +=1
            print "Value at",nthDigit,"is",numb[j-1]       
            break;   
Champernowne()           

JAVA CODE
import java.util.*;
import java.io.*;
public class Champernowne {
    public static void main(String[] args) {
        int nthDigit,counter =0;
        String numb;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter the term whose value has to be found:");
        nthDigit = in.nextInt();
        for(int i = 1; i<=nthDigit; i++) {
            numb ="";
            numb +=i;
            counter +=numb.length();
            if (counter >= nthDigit) {
                counter -= numb.length();
                int j = 0;
                while(counter != nthDigit) {
                    counter++;
                    j++;
                    }
                System.out.println("Value at "+nthDigit+" is "+numb.charAt(j-1));       
                break;
                }
            }   
        }
       
    }   

Friday, August 15, 2014

Stepping Number: Python Code

Python code for stepping number. A number is called
a stepping number if adjacent digits, as well as the
first and last digits, differ by 1.Write a program
to generate all the Stepping numbers( in base 11) in a given range and count it. For example, 8789A9 is a 6-digit base 11 stepping number. 9A0A and 234 are not stepping.

def SteppingNumber():
    numbDigits = [0 for i in range (10000)]
    counter = 0
    lowerLimit = int(input("Enter the lower limit:"))
    upperLimit = int(input("Enter the upper limit:"))
    for j in range(upperLimit+1-lowerLimit):
        flag = False
        numb = j+lowerLimit
        N = numb
        length = len(str(numb))
        baseElevenlen = 0
        b = 0
        while numb > 0 :
            rem = numb%11
            if rem > 9:
                numbDigits[baseElevenlen] = 'A'
            else:  
                numbDigits[baseElevenlen] = rem
            numb = numb//11
            baseElevenlen +=1
               
        numbDigits.reverse()          
        for i in range(baseElevenlen):
            if numbDigits[i] == 'A':
                numbDigits[i] = 10
           
        for i in range(baseElevenlen-1):
            if numbDigits[i] == numbDigits[i+1]+1 or numbDigits[i] == numbDigits[i+1]-1:
                flag = True
            else:
                flag = False
                break;  
           
        if flag == True:
            if numbDigits[0] == numbDigits[baseElevenlen-1]+1 or numbDigits[0] == numbDigits[baseElevenlen-1]-1:
                flag = True  
            else:
                flag = False  
        if flag == True:
            print (N-1," is a Stepping Number")
            print ("In base Eleven (Reverse it)", numbDigits[0:baseElevenlen])
            counter +=1
    print ("Number of stepping numbers(base 11)",counter)
SteppingNumber()

Friday, August 8, 2014

MAGIC SQUARE: Python & JAVA CODE

In recreational mathematics, a magic square is an arrangement of distinct numbers (i.e. each number is used once), usually integers, in a square grid, where the numbers in each row, and in each column, and the numbers in the forward and backward main diagonals, all add up to the same number. A magic square has the same number of rows as it has columns, and in conventional math notation, "n" stands for the number of rows (and columns) it has. Thus, a magic square always contains n2 numbers, and its size (the number of rows [and columns] it has) is described as being "of order n". A magic square that contains the integers from 1 to n2 is called a normal magic square.

La Loubere's method ( for odd order)
The integers from 1 to n2 are inserted along diagonals, starting in the middle of first row and heading in a northeasterly direction. When you go off an edge of the array, which you do at the very first step, continue from the opposite edge. When you bump into a cell that is already occupied, drop down one row and continue.



Python Code

#Magic Square
def MagicSquare():
    N = input("Enter the order of the Magic Square (odd):")
    MS=[[ 0 for row in range(N+1)]for col in range(N+1)]
    row = 1
    col = (N+1)/2
    for i in range(N*N):
         MS[row][col] =i+1
         row -=1
         col +=1
         trow = row
         tcol = col
         if row<=0:
            row = N
         if col>N:
            col = 1
         if MS[row][col] != 0:
            if row == N:
                row = 0           
            if col == 1:
                col = N+1  
            row +=1
            col -=1
            row +=1  
         if row<=0:
            row = N
         if col>N:
            col = 1
    print "OUTPUT~~ MAGIC SQUARE:"
    for i in range (N):
        for j in range (N):
            print MS[i+1][j+1],'\t',
        print
MagicSquare()         




JAVA Code

import java.util.*;
public class MagicSquare {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int[][] MS;
        int row,col,N;
        int trow,tcol;   
        System.out.println("Enter the order of the matrix:(odd)");
        N = in.nextInt();
        MS = new int[N+1][N+1];
        row = 1;
        col = (N+1)/2;
        for(int i = 0; i<N+1;i++)
            for(int j = 0; j<N+1;j++)
                MS[i][j] =0;
        for (int k =1 ; k <=N*N; k++) {
        MS[row][col] =k;
        row--;
        col++;
        trow = row;
        tcol = col;
        if(row<=0)
            row = N;
        if(col>N)
            col = 1;   
        if(MS[row][col] != 0) {
            if ( row == N )
                row = 0;            
            if ( col == 1)
                col = N+1;   
            row++;
            col--;
            row++;
            }   
        if(row<=0)
            row = N;
        if(col>N)
            col = 1;   
        }
        System.out.println("OUTPUT~~ MAGIC SQUARE:");
        for(int i = 1; i<=N;i++) {
            for(int j = 1; j<=N;j++) {
            String t =" ";
                if(MS[i][j]<10) {
                    t = t+" ";
                    t +=MS[i][j];
                    System.out.print("   "+t);
                    }
                else if (10 <= MS[i][j] && MS[i][j] <=99) {
                    t +=MS[i][j];
                    System.out.print("   "+t);
                    }   
                else   
                System.out.print("   "+MS[i][j]);   
                }
            System.out.println();
            }   
        }
    }   

Thursday, August 7, 2014

Telephone Directory ~ ISC COMPUTER SCIENCE PRACTICAL SOLLVED 2000

ISC COMPUTER SCIENCE PRACTICAL SOLLVED 2000, ISC JAVA PROGRAMS
A file contains a list of names and telephone numbers in the following form
AJIT 281050
ANIL 462890
HRISHIKESH 524352
.
.
.
.
.
.
The names contain only one word and the names and telephone numbers
are separated by white spaces. Write an interactive program to :
(i) Create the above file.
(ii) Display the contents in two columns.
(iii) Search a telephone number for a given name (Assure no duplication of names).
(iv) Exit the program.


Test your program using the following data :

AJAY 281050
AJIT 425382
ANIL 525122
AJHAR 528422
HRISHIKESH 524352
JAVAGAL 532673
MONGIA 691383
RAHUL 698114
ROBIN 524899
SACHIN 628266
SAURAV 708294
VENKATESH 492642

Test the (iii) option by searching the telephone numbers of :
(a) AJHAR
(b) SACHIN       

import java.util.*;
import java.io.*;
public class Telephone
    {
    public static void main(String[] args) throws IOException
        {
        String fileName = "Tele.dat";
        String nameCust,temp;
        String teleNumber,S;
        boolean flag;
        Scanner in = new Scanner(System.in);
        FileOutputStream fout = new FileOutputStream(fileName);
        while(true) {
            temp = "";
            flag = false;
            System.out.println("Enter Customer name:");
            nameCust = in.next();
            System.out.println("Enter telephone number");
            teleNumber = in.next();
            temp = nameCust+" "+teleNumber;
            temp = temp.toUpperCase();
            FileReader fr = new FileReader(fileName);   
            BufferedReader br = new BufferedReader(fr);
            while(( S=br.readLine() ) != null) {
                String check ="";
                int j = 0;
                while(S.charAt(j++) != ' ')
                    check += S.charAt(j-1); 
                if (check.equals(nameCust)) {
                    System.out.println("Name already exists, enter a different name:");
                    flag = true;
                    }
                }
            br.close();   
            if(flag == true)
                continue;   
            for( int i = 0; i < temp.length();i++)
                fout.write(temp.charAt(i));
            fout.write('\n');   
            System.out.println("Want to continue? (Y/N)");   
            String a = in.next();
            if ( a.toUpperCase().equals("N"))
                break;
            }
        fout.close();   
       
        String srchTele;
        System.out.println("Enter the customer name to search for telephone number:");
        srchTele = in.next();
        srchTele = srchTele.toUpperCase();
        FileReader fr = new FileReader(fileName);   
        BufferedReader br = new BufferedReader(fr);
        flag = false;
            while(( S=br.readLine() ) != null) {
                String check ="";
                int j = 0;
                while(S.charAt(j++) != ' ')
                    check += S.charAt(j-1); 
                if (check.equals(srchTele)) {                    
                    System.out.println(S.substring(j));
                    flag = true;
                    }
                }
        if( flag == false)
            System.out.println("Customer does not exists:");       
        br.close();       
        }
    }   

Tuesday, August 5, 2014

KEITH NUMBER JAVA CODE

Post by Maths.

import java.util.*;
public class Keith {
    public static void main(String[] args){
        int numb,temp;
        int a,b,c;
        Scanner in = new Scanner(System.in);
        System.out.println("Enter a number:");
        numb = in.nextInt();
        TestKeith tk = new TestKeith(numb);
        tk.initdigitNumb();
        if(tk.isKeith() == true)
            System.out.println(numb+"is a Keith number");
        else
            System.out.println(numb+" is not a Keith number");   
        }
    }
class TestKeith {       
    TestKeith(int numb) {
        numbString = "";
        Numb = numb;
        numbString +=numb;
        digitNumb = new int[numbString.length()];
        }
    public void initdigitNumb() {
        for(int i = 0; i < numbString.length(); i++)
            digitNumb[i] = numbString.charAt(i)-48;
        }   
    public boolean isKeith() {
        int temp=0,j,stop=0;
        flag = false;
        while ( stop <= Numb ) {
            for (int i =0; i < numbString.length(); i++)
                temp +=digitNumb[i];
            if (temp == Numb) {
                flag = true;
                break;
                }
            for (j =0; j < numbString.length()-1; j++)
                digitNumb[j] = digitNumb[j+1];
            digitNumb[j] = temp;   
            stop = temp;
            temp = 0;
            }
        return (flag == false? false : true);   
        }   
    private String numbString;
    private int Numb;
    private int[] digitNumb;   
    private boolean flag;
    }