Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dynamic algorithm in java #88

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions Dynamic_Algoritham/Ugly_numbers.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
// Java program to find nth ugly number
class GFG {

/*This function divides a by greatest
divisible power of b*/
static int maxDivide(int a, int b)
{
while (a % b == 0)
a = a / b;
return a;
}

/* Function to check if a number
is ugly or not */
static int isUgly(int no)
{
no = maxDivide(no, 2);
no = maxDivide(no, 3);
no = maxDivide(no, 5);

return (no == 1) ? 1 : 0;
}

/* Function to get the nth ugly
number*/
static int getNthUglyNo(int n)
{
int i = 1;

// ugly number count
int count = 1;

// check for all integers
// until count becomes n
while (n > count) {
i++;
if (isUgly(i) == 1)
count++;
}
return i;
}

/* Driver Code*/
public static void main(String args[])
{
int no = getNthUglyNo(150);

// Function call
System.out.println("150th ugly "
+ "no. is " + no);
}
}

// This code has been contributed by
// Amit Khandelwal (Amit Khandelwal 1)