Python,C,C++ and JAVA programs for CBSE, ISC, B.Tech and I.T Computer Science and MCA students

The Programming Project Tweet to @pseudo_prime Tweet to @vinod_singh_23

Saturday, November 22, 2014

ISC Computer Science Practical 2011 Number to Words

 ISC Computer Science Practical 2011

Write a program to input a natural number less than 1000 and display it in words.
Test your program on the sample data and some random data.
Sample input and output of the program.Input: 29
Output: TWENTY NINE
Input: 17001
Output: OUT OF RANGE
Input: 119
Output: ONE HUNDRED AND NINETEEN
Input: 500
Output: FIVE HUNDRED 


import java.util.*;
public class NumberWords {
    public static void main(String[] args) {
        ToWords numbObject = new ToWords();
        Scanner in = new Scanner(System.in);
        while (true) {
            System.out.println("Input:");
            int i = in.nextInt();
            if (i >= 1000) {
                System.out.println("Output: OUT OF RANGE");
                continue;
                }
            numbObject.toWord(i);
            System.out.println("Want to input another number? Y/N:");
            String c = in.next();
            if(c.equals("y") || c.equals("Y"))
                continue;
            else
                break;   
            }
        in.close();  
        }
    }
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);
        }  
    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 String word;  
    }  

Friday, November 21, 2014

ISC COMPUTER SCIENCE PRACTICALS 2009 BOUNDARY ELEMENTS

Write a program to declare a matrix A[ ][ ] of order (m*n) where 'm' is the number of rows and
n is the number of columns such that both m and n must be greater than 2 and less than 20.
Allow the user to input positive integers into this matrix. Perform the following tasks on the
matrix:
(a) Sort the elements of the outer row and column elements in ascending order using any
standard sorting technique.
(b) Calculate the sum of the outer row and column elements.
(c) Output the original matrix, rearranged matrix, and only the boundary elements of the
rearranged array with their sum.
Test your program for the following data and some random data.
1. Example :
INPUT : M=3, N=3
1 7 4
8 2 5
6 3 9
OUTPUT :
ORIGINAL MATRIX :
1 7 4
8 2 5
6 3 9
REARRANGED MATRIX :
1 3 4
9 2 5
8 7 6
BOUNDARY ELEMENTS :
1 3 9
8   4
5 7 6
SUM OF OUTER ROW AND OUTER COLUMN = 43

    ISC COMPUTER SCIENCE PRACTICALS 2009 

import java.util.*;
public class OuterRowColumn {
    public static void main(String[] args) {
        int M,N;
        Scanner in = new Scanner(System.in);
        System.out.println("INPUT THE VALUE OF ROW:");
        M = in.nextInt();
        System.out.println("INPUT THE VALUE OF COLUMN:");
        N = in.nextInt();
        while( M > 20 || M < 2 || N > 20 || N < 2) {
            System.out.println("OUT OF RANGE, INPUT AGAIN:");
            M = in.nextInt();
            N = in.nextInt();
            }
        Matrix m = new Matrix(M,N);   
        m.inputMatrix();
        System.out.println("OUTPUT:");
        m.outputMatrix();
        System.out.println();
        m.rearrangedMatrix();
        m.outputMatrix();
        System.out.println();
        m.boundaryElements();
        in.close();
        }
    }   
class Matrix {
    Matrix(int M,int N) {
        row = M;
        col = N;
        Mat = new int[M][N];
        outerRowColSum = 0;
        boundary = new int[2*col+2*(row-2)];
        }
    public void outputMatrix() {
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                System.out.print(Mat[i][j]+" ");
                }
            System.out.println();
            }
        }   
    public void rearrangedMatrix() {
        System.out.println("REARRANGED MATRIX :");
        int k = 0;
        for(int i = 0; i < row; i++)
            for(int j = 0; j < col; j++)
                if(i == 0 || j == 0 || i == row-1 || j == col-1)
                    boundary[k++] = Mat[i][j];
        Arrays.sort(boundary);    // sorting the boundary elements
        k = 0;       
        int i=0,j=0;
        // inserting the sorted boundary elements clockwise
        for ( i = 0; i < col; i++)
            Mat[j][i] = boundary[k++];
        for ( i = 1; i < row; i++)
            Mat[i][col-1] = boundary[k++];    
        for ( i = col-2; i >= 0; i--)
            Mat[row-1][i] = boundary[k++];   
        for ( i = row-2; i >= 1; i--)
            Mat[i][0] = boundary[k++];   
        }   
    public void boundaryElements() {
        System.out.println("BOUNDARY ELEMENTS :");
        int k = 0;
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                if(i == 0 || j == 0 || i == row-1 || j == col-1) { // extracting the boundary elements
                    System.out.print(Mat[i][j]+" ");
                    boundary[k++] = Mat[i][j];
                    outerRowColSum += Mat[i][j];
                    }   
                else
                    System.out.print(" "+" ");       
                }
            System.out.println();
            }   
        System.out.println("SUM OF OUTER ROW AND OUTER COLUMN = "+outerRowColSum);   
        }   
    public void inputMatrix() {
        Scanner in = new Scanner(System.in);
        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                System.out.println("Input the element:");
                Mat[i][j] = in.nextInt();
                }
            }
        }   
    private int[] boundary;   
    private int row;   
    private int col;
    private int[][] Mat;
    private int outerRowColSum;
    }       

Tuesday, November 18, 2014

ISC COMPUTER SCIENCE PRACTICAL 2009 DAY NUMBER

Design a program to accept a day number (between 1 and 366), year (in 4 digits) from the user
to generate and display the corresponding date. Also accept 'N' (1<=N<=100) from the user to
compute and display the future date corresponding to 'N' days after the generated date.
Display error message if the value of the day number, year and N are not within the limit or
not according to the condition specified. Test your program for the following data and some
random data.

Example:

INPUT : DAY NUMBER : 233 YEAR : 2008 DATE AFTER(N) : 17
OUTPUT: 20TH AUGUST 2008 DATE AFTER 17 DAYS : 6TH SEPTEMBER 2008
INPUT : DAY NUMBER : 360 YEAR : 2008 DATE AFTER(N) : 45
OUTPUT: 25TH DECEMBER 2008 DATE AFTER 45 DAYS : 8TH FEBRUARY 2009

ISC Computer Science Practical 2009 Java Code

import java.util.*;
public class DayNumber {
    public static void main(String[] args) {
        int dayNumber,year;
        int dayAfter;
        boolean flag;
        Scanner in = new Scanner(System.in);
        DaysCalculation date = new DaysCalculation();
        do {
            System.out.println("INPUT THE DAY NUMBER:");
            dayNumber = in.nextInt();
            System.out.println("INPUT YEAR:");
            year = in.nextInt();
            System.out.println("INPUT THE VALUE OF N:");
            dayAfter = in.nextInt();
            flag = date.checkDate(dayNumber,year,dayAfter);
            if (flag == false)
                System.out.println("INVALID INPUTS:");
            } while(flag != true);
        date.setDate(dayNumber,year,dayAfter);   
        date.dateSpecifier();   
        in.close();
        }   
    }
class DaysCalculation {
    public void setDate(int dayNumber, int year, int dayAfter) {
        this.dayNumber = dayNumber;
        this.year = year;
        this.dayAfter = dayAfter;
        }
    public boolean checkDate(int dayNumber, int year, int dayAfter) {
        if ( dayNumber < 1 || dayNumber > 365 )
            return false;
            else if ( dayAfter < 1 || dayAfter > 100)
                return false;
                else if (String.valueOf(year).length() != 4)
                    return false;
                    else
                    return true;
        }
    public void dateSpecifier() {
        int m = 0,k=1;
        for(int i = 1; i <= dayNumber; i++) {
            if( checkLeap(year) == true ? k > ldays[m] : k > mdays[m] ) {
                k = 1;
                m++;
                }
            k++;   
            }
        String prefix;   
        prefix = (k-1)%10 == 1 ? "st" : (k-1)%10 == 2 ? "nd" : (k-1)%10 == 3 ? "rd" : "th";
        System.out.println(k-1+prefix+" "+months[m]);   
        for (int i = 1; i <= dayAfter; i++) {
            if( checkLeap(year) == true ? k > ldays[m] : k > mdays[m] ) {
                k = 1;
                m++;
                if(m > 11) {
                    year++;
                    m = 0;
                    }
                }
            k++;   
            }
        prefix = (k-1)%10 == 1 ? "st" : (k-1)%10 == 2 ? "nd" : (k-1)%10 == 3 ? "rd" : "th";
        System.out.println("DATE AFTER "+dayAfter+" DAYS:"+(k-1)+""+prefix+" "+months[m]);       
        }   
    private boolean checkLeap(int year) {
        if(year%400==0)
           leap=true;
        else if (year%100==0)
           leap=false;
        else if (year%4==0)
           leap=true;
        else
           leap=false;
           return leap;
        }    
    private boolean flag;
    private static boolean leap;   
    private int dayNumber,year;
    private int dayAfter;
    String[] months = {"January","Feburary","March","April","May","June","July","August","Sepetember","October","November","December"};
    int[] mdays={31,28,31,30,31,30,31,31,30,31,30,31};
    int[] ldays={31,29,31,30,31,30,31,31,30,31,30,31};   
    }           

Wednesday, October 22, 2014

Square root digital expansion : Problem 80 : Project Euler : Pyhton Code


Square root digital expansion : Problem 80 : Project Euler

It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all.
The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digits is 475.
For the first one hundred natural numbers, find the total of the digital sums of the first one hundred decimal digits for all the irrational square roots.

One of the easy way to solve the problem is to use High Precision Python library for Floating point Numbers

>>> from bigfloat import *
>>> sqrt(2, precision(100))  # compute sqrt(2) with 100 bits of precision
BigFloat.exact('1.4142135623730950488016887242092', precision=100)
 
Nonetheless you have to download the bigfloat package. This method does not give the flavor of maths!
I have rather used the decimal module which provides support for decimal floating point arithmetic and have used Newton - Raphson method to calculate the square root correct to 10**(110) places!

import math
from decimal import *
def sqRootDigitalExpansion():
    def f(x,n):
        getcontext().prec = 130
        return Decimal(x**2-n)
    def fderivative(x):
        getcontext().prec = 130
        return Decimal(2*x)
    n = 1
    totalSum = 0
    while n < 100:    
        if n == 1 or n == 4 or n == 9 or n == 16 or n == 25 or n == 36 or n == 49 or n == 64 or n == 81:
            n = n + 1
            continue
        a = 1
        b = -1
        xn = 0
        error = 0.0;
        x0=a
        while True:
           getcontext().prec = 130   
           (xn)=(x0)-((f(x0,n)/fderivative(x0)))
           (error)=(math.fabs(xn-x0))
           x0=xn
           if error < 10**(-110):
               break
        mylist = str(xn).split(".")
        sumR = 0
        for i in range(len(mylist[0])):   
            sumR = sumR + int(mylist[0][i])
        for i in range (0,100-len(mylist[0])):
            sumR = sumR + int(mylist[1][i])
        print "Digital Sum of the root (100 digits) ",sumR," for the number ",n
        totalSum = totalSum + sumR
        n = n + 1
    print totalSum   
sqRootDigitalExpansion()

Largest exponential : Problem 99 : Project Euler

Largest exponential : Problem 99 : Project Euler

Comparing two numbers written in index form like 211 and 37 is not difficult, as any calculator would confirm that 211 = 2048 < 37 = 2187.
However, confirming that 632382518061 > 519432525806 would be much more difficult, as both numbers contain over three million digits.
Using base_exp.txt (right click and 'Save Link/Target As...'), a 22K text file containing one thousand lines with a base/exponent pair on each line, determine which line number has the greatest numerical value.

NOTE: The first two lines in the file represent the numbers in the example given above.


This is on of the easiest problem of Project Euler! Instead of calculating a^x and b^y actually to determine which one is greater, use the fact from analysis that log x is an increasing function. therefore if  a^x > b^y => x*log a > y*log b



Python Code
import math
def largestExponential():
    maxBE = 0.0
    maxLineNumber = 0
    lineNumber = 1
    val = 0.0
    f = open('base_exp.txt','r')
    for line in f:
        t = line[0:len(line)-1]
        mylist = t.split(",")
        val = float(mylist[1])*math.log(float(mylist[0]))
        if maxBE <= val:
            maxBE = val
            maxLineNumber = lineNumber
        lineNumber = lineNumber + 1   
    print "Maximum value at line Number",maxLineNumber   
largestExponential()   

Reciprocal cycles : Problem 26 : Project Euler : Python Code

Reciprocal cycles : Problem 26 : Project Euler

A unit fraction contains 1 in the numerator. The decimal representation of the unit fractions with denominators 2 to 10 are given:
1/20.5
1/30.(3)
1/40.25
1/50.2
1/60.1(6)
1/70.(142857)
1/80.125
1/90.(1)
1/100.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.

Answer:

Max Length= 985  for Decimal Expansion of 1/ 983 = .001017293997965412004069175991861648016276703967446592065106815869
786368260427263479145473041709053916581892166836215666327568667344
862665310274669379450661241098677517802644964394710071210579857578
840284842319430315361139369277721261444557477110885045778229908443
540183112919633774160732451678535096642929806714140386571719226856
561546286876907426246185147507629704984740590030518819938962360122
075279755849440488301119023397761953204476093591047812817904374364
191251271617497456765005086469989827060020345879959308240081383519
837232960325534079348931841302136317395727365208545269582909460834
181078331637843336724313326551373346897253306205493387589013224821
973550356052899287894201424211597151576805696846388606307222787385
554425228891149542217700915564598168870803662258392675483214649033
570701932858596134282807731434384537131230925737538148524923702950
152594099694811800610376398779247202441505595116988809766022380467
955239064089521871820956256358087487283825025432349949135300

 To solve this problem we have to perform the paper-pencil method of division instead of using inbuilt method of (float) division. Since the divisor if maximum of 3 digits (999) makes the case more easier. Only thing to make note of when to stop the division process, which is best understood upon dividing few examples manually. Try with 1/3, 1/7, 1/8 1/133..... In short a pattern will reappear iff in the process of division by n, let diviList be the collection of of the dividend till the mth step, at the (m+1)th step if the dividend is in diviList, you are done, break!     

Python Code

def reciprocalCycles():
    maxLength = 0
    maxN = 0
    n = 2
    while n < 1000:
        dividend = 1
        divisor = n
        quotient = "."
        diviList = ()
        diviList = diviList + (dividend,)
        while True:
            if dividend < divisor:
                dividend = dividend*10
                if dividend < divisor:
                    dividend = dividend*10
                    quotient = quotient + "0"
                    if dividend < divisor:
                        dividend = dividend*10
                        quotient = quotient + "0"
            if dividend not in diviList:
                diviList = diviList + (dividend,)
            else:
                break
            temp = dividend                   
            dividend = (dividend - (dividend/divisor)*divisor)
            quotient = quotient+str(temp/divisor)   
        if maxLength <= len(quotient):
            maxLength = len(quotient)
            maxN = n   
            q = quotient
        n = n + 1
    print "Max Length=",maxLength," for Decimal Expansion of 1/",maxN,"=",q   
reciprocalCycles()                              

Tuesday, October 21, 2014

Non-abundant sums : Problem 23 : Project Euler : Python Code


Non-abundant sums : Problem 23 : Project Euler

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.

Python Code:

def nonAbundantSums():
    def sumOfDivisors(numb):
        sumD = 0
        if numb == 1:
            return 0
        for d in range(numb/2):
            d = d+1
            if numb%d ==0:
                sumD = sumD + d
        return sumD   
       
    limit = 28123       
    sumNonAbn = 0
    tot = 0
    AbnList = ()
    n = 12
    """ Find all the abundant Numbers"""
    while n <= limit:
        if n < sumOfDivisors(n):
            AbnList = AbnList + (n,)
            tot = tot + 1
        """print n"""   
        n = n+1
    """ A List to mark all the numbers less than limit which can be written as sum of abundant numbers"""
    UniqueAbnList = [0 for i in range(limit+1)]
        
   
    for i in range(tot):
        """ Since the list of abundant numbers is increasing once the limit crosses 15000, the sum will be always > limit """
        if AbnList[i] > 15000:
            break
        for j in range(i,tot):
            if (AbnList[i]+AbnList[j]) <= limit:
                """ Mark the numbers """
                UniqueAbnList[AbnList[i]+AbnList[j]] = 1
            j = j + 1   
        i = i + 1       
    k = 0               
    for i in UniqueAbnList:
        if UniqueAbnList[k] == 0:
            """ Add the unmarked numbers """
            sumNonAbn = sumNonAbn +k
            print k,"Cannot be written as Sum of two Abundant Numbers"
        k = k + 1   
    print sumNonAbn       
nonAbundantSums()