Problem Description:
Write a program to find the nth super ugly number.
The definition of super-ugly is a positive integer and all prime-number factors are within the set of the given one-size-K mass.
For example, give you a collection of 4 prime numbers [2, 7, 13, 19], then [1, 2, 4, 7, 8, 13, 14, 16, 19, 26, 28, 32] are the first 12 super ugly numbers.
Precautions
1: is always super ugly number regardless of the number of sets of the quality of what.
2: The set of mass numbers for you has been arranged in ascending order.
0 < k≤100, 0 < n≤10^6, 0 < Primes[i] < 1000
Example: given n = 6 and the mass number set [2, 7, 13, 19].
The 6th super-ugly number is 13, so 13 is returned as a result.
Code:
Package super Ugly number;
Import java.util.ArrayList;
Import Java.util.Scanner;
Public class Main {
public static void Main (string[] args) {
System. out.println (3/2);
Scanner sc = new Scanner (System. in);
int n = sc.nextint ();
int k = sc.nextint ();
if (k<=0| | k>100) {
return;
}
int primes[] = new int[K];
For (int i = 0; i < primes. Length i++) {
primes[i] = sc.nextint ();
For (int j = 2; J < primes[i]/2+1; J + +) {
if (primes[i]%j==0) {
return;
}
}
}
arraylist<integer> list = new arraylist<integer> ();
List.add (1);
For (int i = 2; I < Math.pow (10, 6); i++) {
if (Issuperuglynumber (I,primes)) {
list.add (i);
}
if (list.size () = =N) {
System. Out.println (list.get (n-1));
Break ;
}
}
}
Recursive thought to determine whether it is super ugly number
private static boolean issuperuglynumber (int i, int[] primes) { /c15>
if(i<primes[0]) return false;
else{
For (int j = primes. Length-1; J >= 0; j--) {
if (i==primes[j]) {
return true;
}
Else if (i>primes[j]&&i%primes[j]==0) {
if (issuperuglynumber (i/primes[j],primes)) {
return true;
}
}else{
continue;
}
}
return false;
}
}
Circular thought judging whether it is super ugly number
Public static boolean issuperuglynumber (int num , int[] p) {
For (int i = 0; i < p.length; i++) {
int j = 0;
While (True) {
if (num% p[i]! = 0) {
Break ;
}else{
num = num/p[i];
continue;
}
}
if (num = = 1) {
return true;
}
}
return false;
}
}
Using the loop and recursive two ideas, two methods can be correctly judged whether to meet the conditions of super-ugly number, here will not put the test results, please self-test
There are still some details of the problem not dealt with, do not care about these ha.
Reprint please indicate the source Oh http://www.cnblogs.com/meng1314-shuai/p/7233403.html
The super ugly number of Java algorithm