Showing posts with label Keith Number. Show all posts
Showing posts with label Keith Number. Show all posts

Keith Number

 //Write a program to accept a number and check it is a Keith number or not.

//A Keith number is an integer n with d digits with the following property. if a fibonacci like sequence

//is formed with the first d terms. ex- 197 is a keith number

//1,9,7,17,33,57,107,197 

import java.util.*;

class keith1

{

    public static void main(String[]args)

    {

        Scanner sc=new Scanner(System.in);

        System.out.println("Enter a no");

        int n=sc.nextInt();//197

        int c=0,k=n,k1=n,s=0,sum=0,r=0,s1=n%10,num=n;//variable c to count the digit,k,k1,num to store the number,s,sum to store the sum,r to store the result,s1 to store the last digit

        while(n>0)

        {

            c=c+1;//3

            s=s+(n%10);//17

            n=n/10;

        }

        int s2=s,c1=c;//variable s2 to store the sum,c1 to store the no of digits

        while(c>0)//3>0 t//2>0 t//1>0 t//0>0 f

        {

            sum=sum+s;//0+17=17//17+16=33//33+24=57

            r=k/(int)Math.pow(10,c-1);//197/100=1//97/10=9//7/1=7

            s=sum-r;//17-1=16//33-9=24//57-7=50

            k=k%(int)Math.pow(10,c-1);//197%100=97//97%10=7//7%1=0

            c--;

           

        }

            if(sum==k1)//50==197 f

            System.out.println("It is a keith no");

            else

            {

        

        while(sum<=k1)//50<=197//93<=197//169<=197

        {

            sum=(2*sum)-s1;//2x50-7=93//2x93-17=169//2x169-33=305

            s1=s2;//17//33//

            if(c1>0)//3>0 t//2>0 t

            {

            s2=s2+(s2-(num/(int)Math.pow(10,c1-1)));//17+(17-197/100)=33//33+(33-97/10)=57

            num=num%(int)Math.pow(10,c1-1);//197%100=97//97%10=7

            }

            c1--;

            if(sum==k1)

            break;

            

        

        }

    if(sum==k1)

    System.out.println("It is a keith no");

    else

    System.out.println("It is not a keith no");

}

}//main method opens

}//class opens



Second largest number in java using ternary operator

 //Largest second number using ternary operator public class Main { public static void main(String[] args) { int a=5,b=6,c=7; int ...