-
Notifications
You must be signed in to change notification settings - Fork 62
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #54 from Mownika25/add-code
algorithm for magic no.
- Loading branch information
Showing
1 changed file
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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 |