From 199a524cf4cb087ee5cfa610e32a88fb4cae45f8 Mon Sep 17 00:00:00 2001 From: Mownika25 Date: Fri, 18 Oct 2019 21:20:50 +0530 Subject: [PATCH] algorithm for magic no. --- Miscellaneous/MagicNumber.java | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 Miscellaneous/MagicNumber.java diff --git a/Miscellaneous/MagicNumber.java b/Miscellaneous/MagicNumber.java new file mode 100644 index 0000000..b8bc3e8 --- /dev/null +++ b/Miscellaneous/MagicNumber.java @@ -0,0 +1,43 @@ +// Java program to find nth +// magic numebr +import java.io.*; + +class MagicNumber +{ +// Function to find nth magic number +static int nthMagicNo(int n) +{ + int pow = 1, answer = 0; + + // Go through every bit of n + while (n != 0) + { + pow = pow*5; + + // If last bit of n is set + if ((int)(n & 1) == 1) + answer += pow; + + // proceed to next bit + // or n = n/2 + n >>= 1; + } + return answer; +} + +// Driver program to test +// above function +public static void main(String[] args)throws IOException +{ + BufferedReader br= new BufferedReader(new InputStreamReader(System.in)); + System.out.println("Enter a no."); + int n = Integer.parseInt(br.readLine()); + + System.out.println(n+"th magic" + + " number is " + nthMagicNo(n)); +} +} + + +// This code is contributed by +// prerna saini