豎式除法模擬


寫這篇博客的目的是為了更好利用數學方法來處理數據,之前遇到了一道題給你a,b,c三個數問a/b小數點后幾位是c,按照我的想法肯定是現將a/b的結果使用函數轉換成字符串,然后直接在字符串中查找,很遺憾對於數據量較大的數根本就不能通過,還好這道水題是我隊友AC通過了,這道題到我手里肯定是通不過的,那我們就來模擬一下豎式除法的過程。

 

看到這個式子是不是回憶起小學學習除法的經歷了吧,這應該是四則運算中最困難的了。

我們來看一下運算過程:

被除數a對除數b整除,得到一個結果,再對余數乘10(十進制),組成新余數,新余數變為新被除數,除數不變,再次進行整除,不斷循環。

也就是a=a%b*10

 

例題1:HDU 2117  http://acm.hdu.edu.cn/showproblem.php?pid=2117

Just a Numble

 

Problem Description
Now give you two integers n m, you just tell me the m-th number after radix point in 1/n,for example n=4,the first numble after point is 2,the second is 5,and all 0 followed
 
Input
Each line of input will contain a pair of integers for n and m(1<=n<=10^7,1<=m<=10^5)
 
Output
For each line of input, your program should print a numble on a line,according to the above rules
 
Sample Input
4 2
5 7
123 123
 
Sample Output
5
0
8
 
題目意思:問1/n后的第m位數是多少。
 1 #include<iostream>
 2 #include<stdio.h>
 3 using namespace std;
 4 int main()
 5 {
 6     int m,n,result,i;
 7     int temp;
 8     while(scanf("%d%d",&n,&m)!=EOF)
 9     {
10         temp=1;
11         for(i=1;i<=m;i++)
12         {
13             temp*=10;
14             result=temp/n;
15             temp=temp%n;
16         }
17         result=result%10;
18         printf("%d\n",result);
19     }
20     return 0;
21 }

 

例2

CF 900B - Position in Fraction

Description

You have a fraction . You need to find the first occurrence of digit c into decimal notation of the fraction after decimal point.

Input

The first contains three single positive integers abc (1 ≤ a < b ≤ 1050 ≤ c ≤ 9).

Output

Print position of the first occurrence of digit c into the fraction. Positions are numbered from 1 after decimal point. It there is no such position, print -1.

Sample Input

Input
1 2 0
Output
2
Input
2 3 7
Output
-1

Hint

The fraction in the first example has the following decimal notation: . The first zero stands on second position.

The fraction in the second example has the following decimal notation: . There is no digit 7 in decimal notation of the fraction.

 

題目意思:問a/b得到的小數中c在小數點后多少位上。

 

 1 #include <iostream>
 2 #include<cstdio>
 3 #include<algorithm>
 4 const int MAX=1e6+10;
 5 using namespace std;
 6 int main()
 7 {
 8     int a,b,c,i,ans;
 9     scanf("%d%d%d",&a,&b,&c);
10     ans=-1;///若沒有找到,即為初始化的-1
11     for(i=1; i<MAX; i++)
12     {
13         a=a*10;
14         if(a/b==c)
15         {
16             ans=i;
17             break;
18         }
19         a=a%b;
20     }
21     printf("%d\n",ans);
22     return 0;
23 }

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM