📜  连续除法后找到数字

📅  最后修改于: 2021-04-27 22:08:30             🧑  作者: Mango

给定两个保存除数数值的数组divrem ,任务是找到一个数,该数在被div数组的元素连续除以后,剩下的数将留在rem数组中。
注意:来自第一个除法的商将被第二个元素除,然后将得到的商除以第三个(与给定的余数匹配),依此类推。
例子:

方法:

  • 将最后余数的值存储在变量num中
  • n-2向后遍历数组到0 ,并将num更新为num = num * div [i] + rem [i]
  • 最后打印num

下面是上述方法的实现:

C++
// C++ program to implement above approach
#include 
using namespace std;
 
// Function to find the number
int findNum(int div[], int rem[], int N)
{
    int num = rem[N - 1];
 
    for (int i = N - 2; i >= 0; i--) {
        num = num * div[i] + rem[i];
    }
 
    return num;
}
 
// Driver Code
int main()
{
    int div[] = { 8, 3 };
    int rem[] = { 2, 2 };
    int N = sizeof(div) / sizeof(div[0]);
 
    cout << findNum(div, rem, N);
 
    return 0;
}


Java
// Java implementation of the above approach
 
public class GFG{
     
    // Function to find the number
    static int findNum(int div[], int rem[], int N)
    {
        int num = rem[N - 1];
     
        for (int i = N - 2; i >= 0; i--) {
            num = num * div[i] + rem[i];
        }
     
        return num;
    }
 
 
     // Driver Code
     public static void main(String []args){
            int div[] = { 8, 3 };
            int rem[] = { 2, 2 };
            int N = div.length;
   
            System.out.println(findNum(div, rem, N));
 
     }
     // This code is contributed by ANKITRAI1
}


Python3
# Python 3 program to implement
# above approach
 
# Function to find the number
def findNum(div, rem, N):
    num = rem[N - 1]
    i = N - 2
    while(i >= 0):
        num = num * div[i] + rem[i]
         
        i -= 1
 
    return num
 
# Driver Code
if __name__ == '__main__':
    div = [8, 3]
    rem = [2, 2]
    N = len(div)
 
    print(findNum(div, rem, N))
 
# This code is contributed by
# Surendra_Gangwar


C#
// C# implementation of the
// above approach
using System;
 
class GFG
{
 
// Function to find the number
static int findNum(int []div,
                   int []rem, int N)
{
    int num = rem[N - 1];
 
    for (int i = N - 2; i >= 0; i--)
    {
        num = num * div[i] + rem[i];
    }
 
    return num;
}
 
 
// Driver Code
static public void Main ()
{
    int []div = { 8, 3 };
    int []rem = { 2, 2 };
    int N = div.Length;
 
    Console.WriteLine(findNum(div, rem, N));
 
}
}
 
// This code is contributed by ajit


PHP
= 0; $i--)
    {
        $num = $num * $div[$i] + $rem[$i];
    }
 
    return $num;
}
 
// Driver Code
$div = array( 8, 3 );
$rem = array(2, 2 );
$N = sizeof($div);
 
echo findNum($div, $rem, $N);
 
// This code is contributed by ajit
?>


Javascript


输出:
18
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”