w3resource

Java: Check whether a number is a Keith Number or not

Java Numbers: Exercise-26 with Solution

Write a Java program to check whether a number is a Keith Number or not.

In recreational mathematics, a Keith number or repfigit number (short for repetitive Fibonacci-like digit) is a number in the following integer sequence:
14, 19, 28, 47, 61, 75, 197, 742, 1104, 1537, 2208, 2580, 3684, 4788, 7385, 7647, 7909, 31331, 34285, 34348, 55604, 62662, 86935, 93993, 120284, 129106, 147640, 156146, 174680, 183186, 298320, 355419, 694280, 925993,

Test Data
Input a number: 75

Sample Solution:

Java Code:

import java.util.Scanner;
public class Example26  {

   public static void main(String[] args) { 

     Scanner sc = new Scanner( System.in ); 
     System.out.print("Input a number: "); 
     int n = sc.nextInt(); 
     int n1 = n;
     String s = Integer.toString(n);
     int d=s.length();
     int arr[]=new int[n];
     int i, sum; 
     for(i=d-1; i>=0; i--)
     {
         arr[i]=n1 % 10;
         n1=n1/10;
          
     }
      
     i=d; sum=0;
     while(sum<n)
     {
         sum = 0;
         for(int j=1; j<=d; j++)
         {
             sum=sum+arr[i-j];
         }
         arr[i]=sum;
         i++;
     }
 
    if(sum==n)
        System.out.println("Keith Number");
     else
        System.out.println("Not a Keith Number");
    }
}

Sample Output:

Input a number: 75                                                                                        
Keith Number 

Flowchart:

Flowchart: Check whether a number is a Keith Number or not

Java Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Java program to print the first 15 numbers of the Pell series.
Next: Write a Java program to create the first twenty Hamming numbers.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.

Java: Tips of the Day

IsPowerOfTwo

Checks if a value is positive power of two.

To understand how it works let's assume we made a call IsPowerOfTwo(4).

As value is greater than 0, so right side of the && operator will be evaluated.

The result of (~value + 1) is equal to value itself. ~100 + 001 => 011 + 001 => 100. This is equal to value.

The result of (value & value) is value. 100 & 100 => 100.

This will value the expression to true as value is equal to value.

public static boolean isPowerOfTwo(final int value) {
    return value > 0 && ((value & (~value + 1)) == value);
}

Ref: https://bit.ly/3sA5d4I

 





We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook