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

The Programming Project: Champernowne's constant: JAVA & Python CODE Problem 40

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

No comments:

Post a Comment