zoukankan      html  css  js  c++  java
  • n数乘积第m小


    这是从Java贴吧看到的一道面试题,看了别人的解题思路实现的....

    如题:

    n个数,他们的乘积可得到一些其它的数,求第m小的。

    输入格式:
    n m
    n1 n2 n3 ...

    例:
    输入:
    3 8
    2 3 5

    输出:
    10

    如何得来:2, 3, 4(2*2), 5, 6(2*3), 8(2*2*2), 9(3*3), 10(2*5)





    思路:
        不论它们怎么排列组合的乘积得到的数字都还能被这些数字约掉,
        所以只需要从最小的开始进行因式分解判断就可以了。


     1 public class Main {
     2 
     3     public static void main(String[] args) {
     4         
     5         Scanner sc=new Scanner(System.in);
     6         
     7         int n=sc.nextInt();
     8         int m=sc.nextInt();
     9         
    10         int a[]=new int[n];
    11         for(int i=0;i<a.length;i++){
    12             a[i]=sc.nextInt();
    13         }
    14         
    15         Arrays.sort(a);
    16         
    17         long ans=a[0];
    18         while(m>0){
    19             if(factorSolve(ans,a)) m--;
    20             ans++;
    21         }
    22         
    23         System.out.println(--ans);
    24     }
    25     
    26     public static boolean factorSolve(long n,int a[]){
    27         if(n==1) return true;
    28         for(int i=0;i<a.length;i++){
    29             if(n%a[i]==0 && factorSolve(n/a[i],a)) return true;
    30         }
    31         return false;
    32     }
    33 }



  • 相关阅读:
    Python面向对象
    Python函数
    Linux之路
    Python之路
    函数
    动态参数
    python模块的运行机制以及time模块格式转换
    Python PEP8代码规范_20180614
    Oracle 分页查询方法和效率分析
    oracle 12c数据库启动(包含CDB和PDB)以及常见异常处理
  • 原文地址:https://www.cnblogs.com/cc11001100/p/5788872.html
Copyright © 2011-2022 走看看