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

The Programming Project: August 2014

Sunday, August 31, 2014

Consecutive prime sum :Problem 50

Consecutive prime sum :Problem 50

The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.
Which prime, below one-million, can be written as the sum of the most consecutive primes?

Problem Source : Euler Project

Python Code 

import math
def largestSumofConsecutivePrime():
    def checkPrime(numb):
        prime = True
        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
    primeList = ()   
    cumiSumList = ()
    sumd = 0
    count = 0
    cumiSumList =cumiSumList+(0,)
    maxPrime = 0
    maxLength = 0
    for prime in range(1000000):
        prime = prime + 2
        if checkPrime(prime) == True:
            primeList = primeList+(prime,)
            sumd = sumd + prime
            cumiSumList =cumiSumList+(sumd,)
            count = count + 1
    #print primeList
    #print cumiSumList
    for i in range(count):
        for j in range(i+1):
            if cumiSumList[i]-cumiSumList[j] > 1000000:   
                break
            if (cumiSumList[i]-cumiSumList[j]) in primeList:
                if i-j > maxLength:
                    maxLength = i-j
                    maxPrime = cumiSumList[i] - cumiSumList[j]
    print maxLength,maxPrime                   
largestSumofConsecutivePrime()                


Saturday, August 30, 2014

Lychrel numbers : Problem 55 Euler Project

Lychrel numbers : Problem 55

If we take 47, reverse and add, 47 + 74 = 121, which is palindromic.
Not all numbers produce palindromes so quickly. For example,
349 + 943 = 1292,
1292 + 2921 = 4213
4213 + 3124 = 7337
That is, 349 took three iterations to arrive at a palindrome.
Although no one has proved it yet, it is thought that some numbers, like 196, never produce a palindrome. A number that never forms a palindrome through the reverse and add process is called a Lychrel number. Due to the theoretical nature of these numbers, and for the purpose of this problem, we shall assume that a number is Lychrel until proven otherwise. In addition you are given that for every number below ten-thousand, it will either (i) become a palindrome in less than fifty iterations, or, (ii) no one, with all the computing power that exists, has managed so far to map it to a palindrome. In fact, 10677 is the first number to be shown to require over fifty iterations before producing a palindrome: 4668731596684224866951378664 (53 iterations, 28-digits).
Surprisingly, there are palindromic numbers that are themselves Lychrel numbers; the first example is 4994.
How many Lychrel numbers are there below ten-thousand?

Problem Source : Euler Project

Python Code


def lychrelNumbers():
    counter = 50
    lychrelCounter = 0
    def reverse(text):
            if len(text) <= 1:
                return text
            return reverse(text[1:]) + text[0]
    for i in range(10000):
        i = i+1
        count = 0
        k = i
        while True:
            s1 = str(k)
            s2 = reverse(s1)
            s3 = str(int(s1)+int(s2))
            if s3 != reverse(s3):
                count = count + 1
            else:
                break   
            k = int(s3)
            if count > counter:
                lychrelCounter = lychrelCounter + 1
                break
    print lychrelCounter
lychrelNumbers()               
                   
       
       

Amicable numbers : Problem 21 Euler Project

Amicable numbers : Problem 21

Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n).
If d(a) = b and d(b) = a, where ab, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.

Problem Source : Euler Project

Python Code

def amicableNumber():
    totalSum = 0
    def sumOfDivisors(numb):
        sumD = 0
        for d in range(numb/2):
            d = d+1
            if numb%d ==0:
                sumD = sumD + d
        return sumD
    for i in range(10000-1):
        i = i+1
        if i == sumOfDivisors(i):
            continue
        if i == sumOfDivisors(sumOfDivisors(i)):
            print i
            totalSum = totalSum + i   
    print "Evaluate the sum of all the amicable numbers under 10000:",totalSum
amicableNumber()               

Lexicographic permutations:Problem 24

Lexicographic permutations:Problem 24

A permutation is an ordered arrangement of objects. For example, 3124 is one possible permutation of the digits 1, 2, 3 and 4. If all of the permutations are listed numerically or alphabetically, we call it lexicographic order. The lexicographic permutations of 0, 1 and 2 are:
012   021   102   120   201   210
What is the millionth lexicographic permutation of the digits 0, 1, 2, 3, 4, 5, 6, 7, 8 and 9?

Problem Source Euler Project

C Code

#include<stdio.h>
#include<malloc.h>
void sort(char *permutation,int n,int pos);
void replace_min (char *permutation,int n,int pos);
int main()
{
char alpha[]={'0','1','2','3','4','5','6','7','8','9','K','L','M',
          'N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
int n,i,flag=1,pos;
long int tot=0;
char *permutation;
printf("\n Enter the numbr of objects (max values is 26):");
scanf("%d",&n);
permutation =(char *)malloc(n*sizeof(char));
for(i=0;i<n;i++)
    permutation[i]=alpha[i];
printf("\n The permutations are:\n");
printf("\t\t      ");
for(i=0;i<n;i++)
    printf("%c",permutation[i]);
    tot=1;
while(flag)
    {
    pos=-1;
    for(i=n-1;i>=1;i--)
        {
        if(permutation[i-1]<permutation[i])
             {
             pos=i-1;
             flag=1;
             break;
             }
        }
        if(pos==-1)
            {
            flag=0;
            break;
            }
    replace_min(permutation,n,pos);
    sort(permutation,n,pos);
   printf("\n");
    printf("\t\t      ");
    for(i=0;i<n;i++)
        printf("%c",permutation[i]);
    tot++;
    printf(">>>>>>>>>>%ld",tot);
    if (tot==1000000)
        break;
    }
//printf("\n Total number of permutation is: %ld",tot);
return 0;
}
void sort(char *permutation,int n,int pos)
{
    int i,j;
   char temp='A';
    for(i=pos+1;i<n-1;i++)
        {
        for(j=pos+1;j<n-1;j++)
            {
            if(permutation[j]>permutation[j+1])
                {
                temp=permutation[j+1];
                permutation[j+1]=permutation[j];
                permutation[j]=temp;
                }
            }
        }
  return;
}
void replace_min(char *permutation,int n,int pos)
{
  char min='Z',temp;
  int k,min_pos=0;
  for(k=pos+1;k<n;k++)
    {
        if(permutation[k]>permutation[pos])
            {
            if(permutation[k]<min)
                {
                min=permutation[k];
                min_pos=k;
                }
            }
    }
    temp=permutation[min_pos];
    permutation[min_pos]=permutation[pos];
    permutation[pos]=temp;
    return;
}

1000-digit Fibonacci number : Problem 25

1000-digit Fibonacci number : Problem 25

The Fibonacci sequence is defined by the recurrence relation:
Fn = Fn−1 + Fn−2, where F1 = 1 and F2 = 1.
Hence the first 12 terms will be:
F1 = 1
F2 = 1
F3 = 2
F4 = 3
F5 = 5
F6 = 8
F7 = 13
F8 = 21
F9 = 34
F10 = 55
F11 = 89
F12 = 144
The 12th term, F12, is the first term to contain three digits.
What is the first term in the Fibonacci sequence to contain 1000 digits?

Problem Source: Euler Project

Python Code

def ThousandDigitFiboNumbers():
    a = 1
    b = 1
    nextSum = 0
    totalSum = 2
    while True:
        nextSum = a+b
        a = b
        b = nextSum
        totalSum = totalSum + 1
        if len(str(nextSum)) == 1000:
            break
    print "first term in the Fibonacci sequence to contain 1000 digits:",totalSum       
ThousandDigitFiboNumbers()

Power digit sum : Problem 16 Python Code

Power digit sum : Problem 16 Euler Project

215 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.
What is the sum of the digits of the number 21000?

Python Code

def powerDigitSum():
    l = 2**1000
    strNumb = str(l)
    sumFact = 0
    for i in range(len(strNumb)):
        sumFact = sumFact + int(strNumb[i])
    print "sum of the digits in the number! is",sumFact
powerDigitSum()

Factorial digit sum : Problem 20 Euler Project Pyhton Code

Factorial digit sum : Problem 20 Euler Project

n! means n × (n − 1) × ... × 3 × 2 × 1
For example, 10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27.
Find the sum of the digits in the number 100!


Python Code

def main():
    x=input("Enter a natural number:")
    x1 = x
    l=1
    for i in range(x):
        l=l*x
        x=x-1
    print l
    strNumb = str(l)
    sumFact = 0
    for i in range(len(strNumb)):
        sumFact = sumFact + int(strNumb[i])
    print "sum of the digits in the number",x1,"! is",sumFact
main()

Counting Sundays Problem : Euler Project : Problem 19

Counting Sundays : Problem 19 Euler Project

You are given the following information, but you may prefer to do some research for yourself.
  • 1 Jan 1900 was a Monday.
  • Thirty days has September,
    April, June and November.
    All the rest have thirty-one,
    Saving February alone,
    Which has twenty-eight, rain or shine.
    And on leap years, twenty-nine.
  • A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400.
How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?


JAVA Code

import java.util.*;
import java.io.*;
public class euler19 {
    public static void main(String[] args) throws IOException {
        int day=1,month=1,year=1900;
        int day1=31,month1=12,year1=2000;
        DaysCalculation date = new DaysCalculation();
        DaysCalculation date1 = new DaysCalculation();
        date.setDate(day,month,year);   
        System.out.println("Number of Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000):"+date.countDays(day1,month1,year1));       
        }
    }
class DaysCalculation {
    public void setDate(int d, int m, int y ){
        day = d;
        month = m;
        year = y;
        sundayCount = 0;
        }
    public int countDays(int day1, int month1, int year1 ){
        boolean small = false;
        int weekDpointer=0;
        if (year == year1)
            if (month == month1)
                if (day < day1)
                    small = true;
                else
                    small = false;       
            else if ( month < month1)
                small = true;
            else
                small = false;           
        else if( year < year1)
            small = true;
        else
            small = false;
        if (small == false) {
            int td,tm,ty;
            td = day;
            day = day1;
            day1 = td;
            tm = month;
            month = month1;
            month1 = tm;
            ty = year;
            year = year1;
            year1=ty;
            }   
        while (year < year1+1) {
            /*if(weekDpointer == 6 && day == 1) {
                System.out.println(day+"/"+month+"/"+year+weekDays[weekDpointer]);
                sundayCount++;
            }*/
            day++;
            weekDpointer++;
            if(weekDpointer >= 7)
                weekDpointer %=7;
            if (checkLeap(year) == true) {
                if (day > ldays[month-1]) {
                    day = 1;
                    month ++;
                    if(weekDpointer == 6 && day == 1 && year != 1900) {
                        System.out.println(day+"/"+month+"/"+year+"~~"+weekDays[weekDpointer]);
                        sundayCount++;
                        System.out.println();
                    }
                    if (month > 12) {
                    month = 1;   
                    year++;
                    }
                }
            }   
            else {
                if (day > mdays[month-1]) {
                    day = 1;
                    month ++;
                    if(weekDpointer == 6 && day == 1 && year != 1900) {
                        System.out.println(day+"/"+month+"/"+year+"~~"+weekDays[weekDpointer]);
                        sundayCount++;
                        System.out.println();
                    }
                    if (month > 12) {
                    month = 1;   
                    year++;
                    }
                }   
            }
        } // end of while   
        return sundayCount;       
        }
    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 day,month,year;
    private int sundayCount;
    String[] weekDays ={"Mon","Tue","Wed","Thu","Fri","Sat","Sun"};
    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};   
    }       

Summation of primes : Python Code Problem 10 Euler Project

Summation of primes : Problem 10

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

Problem Source: Euler Project

Python Code

import math
def sumPrime():
    primeSum = 17
    def checkPrime(numb):
        prime = True
        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
    for i in range(2000000-1):
        i = i+2
        if i%2 == 0 or i%3 == 0 or i%5 ==0 or i%7 == 0:
            continue
        if checkPrime(i) == True:
            primeSum = primeSum+i
            
    print "Sum of all the primes below two million:",primeSum        
sumPrime()

Special Pythagorean triplet : Python Code : Euler Project : Problem 9

A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a2 + b2 = c2
For example, 32 + 42 = 9 + 16 = 25 = 52.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.

Problem Source: Euler Project

Python Code

def specialPythagoreanTriplet():
    product = 1
    flag = False
    for  a in range (1000):
        a = a+1
        for b in range(1000):
            b = b+1
            if a+b > 1000 or a == b:
                continue
            for c in range(1000):
                c = c+1
                if a+b+c != 1000 or c%4 == 2 or c%4 == 3:
                    continue
                if a**2+b**2 == c**2 and a+b+c == 1000:
                    product = a*b*c   
                    print a,b,c
                    flag = True
                    break
            if flag == True:
                break       
        if flag == True:
            break       
    print "The prouct abc:",product       
specialPythagoreanTriplet()

Thursday, August 28, 2014

Smallest multiple : Euler Project

Smallest multiple : Problem 5

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?

The answer to this problem is to find the l.c.m of the numbers 1,2,3,.......,18,19,20

Python Code

def smallestMultiple():
    lcm = 2
    tup = [0 for i in range(20)]
    for i in range(20):
        tup[i] = i+1
    while lcm > 1:
        count = 0
        for i in range(20):
            if lcm%tup[i] == 0:
                count = count+1
            else:
                break   
        if count != 20:
            lcm = lcm+1       
        else:
            break
    print lcm
smallestMultiple()           
           

10001st prime : Problem 7 Euler Project

10001st prime:Problem 7

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?

Python Code

import math
def countPrime():
    primeCount = 0
    prime = 1
    counter = 2
    def checkPrime(numb):
        prime = True
        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
    while primeCount < 10001:
         if checkPrime(counter) == True:
             primeCount = primeCount+1
             prime = counter
         counter = counter + 1   
    print "10001 st Prime is",prime        
countPrime()

Largest palindrome product: Euler Project Problem 4

Largest palindrome product

Problem 4

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.

Python Code

def largestPalindromeProduct():
    largestPalin = 1
    def checkPalin(strNumb):
        palin = True
        for i in range(len(strNumb)+1/2):
            if strNumb[i] == strNumb[len(strNumb)-1-i]:
                continue
            else:
                palin = False     
        if palin == False:
            return False
        else:
            return True
    for i in range(999-100+1):
        i = i+100
        for j in range(999-100+1):
            j = j+100
            numb = i*j
            strNumb = str(numb)
            if strNumb[0] != strNumb[len(strNumb)-1]:
                continue
            if checkPalin(strNumb) == True:
                if largestPalin < numb:
                    largestPalin = numb
                    a = i
                    b = j
    print "Largest Palindrome formed by the product of three digit numbers is:",largestPalin,"=",a,"x",b
largestPalindromeProduct()           

Multiples of 3 and 5 : Euler Project

Multiples of 3 and 5

Problem 1

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.

Project Euler.net

Python Code

def sumMultiples():
    sumTotal = 0
    lwrBnd = 1
    uprBnd = input("Enter the upper bound:")
    uprBnd = uprBnd-1
    print ("Enter the numbers sum of whose multiples are to be found:")
    a = input("First Number:")
    b = input("Second Number:")
    lcm = 2
    while lcm > 1:
        if lcm%a == 0 and lcm%b == 0:
            break
        else:
            lcm = lcm+1
    lastTerm = a*(uprBnd/a)   
    n = lastTerm/a
    sumTotal = sumTotal + a*(n*(n+1))/2
    lastTerm = b*(uprBnd/b)
    n = lastTerm/b
    sumTotal = sumTotal + b*(n*(n+1))/2
    lastTerm = lcm*(uprBnd/lcm)
    n = lastTerm/lcm
    sumTotal = sumTotal - lcm*(n*(n+1))/2
    print "Required Sum is",sumTotal
sumMultiples()   
   

Even Fibonacci numbers: Python Code

Even Fibonacci numbers

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.

Euler Project Problem 2

Python Code

def sumEvenFiboNumbers():
    a = 1
    b = 2
    nextSum = 0
    totalSum = 2
    while True:
        nextSum = a+b
        a = b
        b = nextSum
        if nextSum <= 4000000:
            if nextSum%2 == 0:
                totalSum = totalSum+nextSum
        else:
            break
    print "Sum of even fibo terms less than 4 million is:"totalSum       
sumEvenFiboNumbers()   

Largest prime factor: Python Code : Problem 3

Largest prime factor : Problem 3

The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
http://projecteuler.net/problem=3 

Answer:  6857

Python Code

import math
def largestPrimeFactor():
    numb = input("Enter the number:")
    pf = 1
    def checkPrime(numb):
        prime = True
        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
    for i in range(int(math.sqrt(numb))):
        i = i+2
        if checkPrime(i) == True and numb % i == 0:
            print i
            pf = i
    print "Largest Prime factor of",numb,"is:",pf
largestPrimeFactor()                        


Wednesday, August 27, 2014

Strong Achilles Numbers: Python Code

A positive integer n is powerful if p2 is a divisor of n for every prime factor p in n.
A positive integer n is a perfect power if n can be expressed as a power of another positive integer.
A positive integer n is an Achilles number if n is powerful but not a perfect power. For example, 864 and 1800 are Achilles numbers: 864 = 25·33 and 1800 = 23·32·52.
We shall call a positive integer S a Strong Achilles number if both S and φ(S) are Achilles numbers.1
For example, 864 is a Strong Achilles number: φ(864) = 288 = 25·32. However, 1800 isn't a Strong Achilles number because: φ(1800) = 480 = 25·31·51.
There are 7 Strong Achilles numbers below 104
How many Strong Achilles numbers are there below 108?
1 φ denotes Euler's totient function.

Problem taken from Euler Project

Python Code:

# STRONG ACHILLIES NUMBER

def strongAchilliesNumber():
    strongAchilliescounter = 0
    a = input("Enter the lower limit (must be >= 1)")
    b = input("Enter the upper limit(must be <= 10^8)")
    def checkPrime(numb):
        prime = True
        for i in range(numb/2):
            i = i+2
            if numb%i == 0:
                prime = False
                break
        if numb == 2:
            return True
        else:           
            return prime
   
    def calculatePhiNumber(number):
        phiNumber = 1
        for i in range(number/2):
            i = i+2
            powr = 0
            if checkPrime(i) == True and number % i == 0:
                powr = powr+1
                numb = number/i 
                while numb % i == 0:
                    powr = powr+1
                    numb = numb/i
                phiNumber = phiNumber*(pow(i,powr)-pow(i,powr-1))
        return phiNumber
                            
    def checkPowerful(number):
        powerful = True   
        phiNumber = 1   
        powr = 0
        powersList = ()
        maxPower = 0
        for i in range(number/2):
            i = i+2
            powr = 0
            if checkPrime(i) == True and number % i == 0:
                #print i
                powr = powr+1
                numb = number/i 
                while numb % i == 0:
                    powr = powr+1
                    numb = numb/i
                if maxPower < powr:
                    maxPower = powr
                powersList = powersList+(powr,)
                if powr < 2:
                    powerful = False
                    break
        #print powersList,maxPower           
        if powerful == False:
            return False
        else:
            perfect  = True   
            for l in range(maxPower-1):
                l = l+2
                #print ">",l
                temp = True
                for p in powersList:
                    if p%l != 0:        
                        temp = False
                if temp == False:
                    perfect = False
                else:
                    perfect = True
                    break
            if perfect == False:
                return True
            else:
                return False
    for i in range(b):           
        number = i+a
        if checkPowerful(number) == True:
            if checkPowerful(calculatePhiNumber(number)) == True:
                strongAchilliescounter = strongAchilliescounter + 1
                print number,"is a Strong Achilles number:"
            else:
                print number,"is an Achilles number but not a Strong Achillies number:"
                continue   
        else:
            print number,"is not an Achilles number:"
            continue
    print "Total number of Strong Achilles number is:",strongAchilliescounter                           
strongAchilliesNumber()       


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;
    }