Tuesday, July 16, 2019

Keith Number | Programming | Eclipse JAVA | Follow on Youtube for more


import java.util.*;
public class keith_number
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number");
String s = sc.next();//taking it as String input
int length = s.length();//taking the string length
int n1 = Integer.parseInt(s);//converting the string into integer
int n2 = n1;//making copy of the number for digit separation operation
int a[] = new int[100];
int insert = length;
while(n2!=0)
{
int mod = n2%10;
a[--insert] = mod;//each digits are stored in array separately
n2 = n2/10;
}
int flag = length;
int sum = 0;
int count= 0;
while(true)//Going for infinite loop
{
for(int i=count;i<flag;i++)//adding last n numbers, where n stands for number of digits
{
sum += a[i];
}
if(sum>n1)//if the sum exceeds the original number, we exit the program
{
System.out.println(n1+" is not a Keith Number");
System.exit(0);
}
if(sum==n1)//if sum is equal to number, than it is a Keith number
{
System.out.println(n1+" is a Keith Number");
System.exit(0);
}
a[flag++] = sum;//adding the sum back to the array, and length of array iteration also exceeds
count++;//increasing the array starting value
sum=0;//initializing the sum back to zero
}
}
}
/*
A n digit number x is called Keith number if it appears in a special sequence
 (defined below) generated using its digits. The special sequence has first n terms
 as digits of x and other terms are recursively evaluated as sum of previous n terms.

The task is to find if a given number is Keith Number or not.

Examples:

Input : x = 197
Output : Yes
197 has 3 digits, so n = 3
The number is Keith because it appears in the special
sequence that has first three terms as 1, 9, 7 and
remaining terms evaluated using sum of previous 3 terms.
1, 9, 7, 17, 33, 57, 107, 197, .....

Input : x = 12
Output : No
The number is not Keith because it doesn't appear in
the special sequence generated using its digits.
1, 2, 3, 5, 8, 13, 21, .....

Input : x = 14
Output : Yes
14 is a Keith number since it appears in the sequence,
1, 4, 5, 9, 14, ...
 */

No comments:

Post a Comment

ICSE COMPUTER SCIENCE SPECIMEN PAPER | QUESTION 7 | PLEASE DO WATCH THE VIDEO

  import  java.util.*; class icse_specimen_1 {     public static void main(String[] args)     {         Scanner sc1 = new Scanner(System.in)...