没有很好的思路,只想到了逐渐逼近的方式,应该还有更好的算法

  1 public class Solution {
  2     int GetNum(int A, int B)//最小公倍数
  3         {
  4             int temp = 0;
  5             int num1 = A;
  6             int num2 = B;
  7             while(B != 0)
  8             {
  9                 temp = A % B;
 10                 A = B;
 11                 B = temp;
 12             }
 13 
 14             return (num1 * num2) / A;
 15         }
 16 
 17     public int NthMagicalNumber(int N, int A, int B) {
 18             double min = Math.Min(A, B);
 19             if (N == 1)
 20                 return (int)(min % (Math.Pow(10, 9) + 7));
 21 
 22             if (A == B)//两数相等直接求积
 23             {
 24                 return (int)(((double)A * (double)N) % (Math.Pow(10, 9) + 7));
 25             }
 26 
 27             double max = Math.Max(A, B);
 28 
 29             if (max % min == 0)//一数为另一数倍数直接求积
 30             {
 31                 double minValue = (double)N * (double)min;
 32                 return (int)(minValue % (Math.Pow(10, 9) + 7));
 33             }
 34             else
 35             {
 36                 double temp = GetNum((int)min, (int)max);//最小公倍数
 37                 double num = N;
 38                 double minValue;
 39                 int delt;
 40                 int tempDelt;
 41                 double ret;
 42                 int change;
 43                 while (true)
 44                 {
 45                     minValue = num * min;
 46                     delt = (int)(minValue / max);
 47                     tempDelt = (int)(minValue / temp);
 48 
 49                     if ((num + delt - tempDelt) > N+1)//递进次数
 50                     {
 51                         num -= (int)((num + delt - tempDelt - N) / 2);
 52                         continue;
 53                     }
 54 
 55                     change = (int)num + delt - tempDelt - N;
 56 
 57                     if (change > 0)
 58                     {
 59                         if (delt * max > num *min)//大数次数去1
 60                         {
 61                             ret = Math.Max((delt - change) * max, num * min);
 62                         }
 63                         else if (delt * max == num * min)//同时去1
 64                         {
 65                             ret = Math.Max((delt-change) * max, (num - change) * min);
 66                         }
 67                         else//小数去1
 68                         {
 69                             ret = Math.Max(delt * max, (num-change) * min);
 70                         }
 71                         
 72                     }
 73                     else
 74                     {
 75                         ret = Math.Max(delt * max, num * min);
 76                     }
 77                         
 78                     return (int)(ret % (Math.Pow(10, 9) + 7));
 79                 }
 80                 
 81             }
 82     }
 83 }