Looooops

链接:http://acm.hust.edu.cn/vjudge/problem/21464/origin

题目:A Compiler Mystery: We are given a C-language style for loop of type
for (variable = A; variable != B; variable += C)

  statement;

I.e., a loop which starts by setting variable to value A and while variable is not equal to B, repeats statement followed by increasing the variable by C. We want to know how many times does the statement get executed for particular values of A, B and C, assuming that all arithmetics is calculated in a k-bit unsigned integer type (with values 0 <= x < 2 k) modulo 2 k.


题意:for(int i=a;i!=b;i+=c) sec;这是一个循环,如果i的值超过了存储上限会对存储上限取模,在再进行计算,问sec语句执行几次。

分析:一样的扩展欧几里得问题,假设上限为k转化后为求cx+ky=b-a的x的一个特解。带入模板可求。

题解:
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <string>
#include <cstring>
#include <functional>
#include <cmath>
#include <cctype>
#include <cfloat>
#include <climits>
#include <complex>
#include <deque>
#include <list>
#include <set>
#include <utility>
#define rt return
#define fr freopen("in.txt","r",stdin)
#define fw freopen("out.txt","w",stdout)
#define ll long long
#define ull unsigned long long
#define detie ios_base::sync_with_stdio(false);cin.tie(false);cout.tie(false)
#define pii pair<int,int>
#define lowbit(x) x&(-x)
using namespace std;
#define maxi 0x3f3f3f3f
#define MAX 100010

ll gcd(ll a, ll b)//小心b为零的情况,保证输入的时候b不为零
{
	rt (a%b) ? gcd(b, a%b) : b;
}

ll exgcd(ll a, ll b, ll &x, ll &y)//小心b为零的情况,保证输入的时候b不为零
{
	if (b == 0)
	{
		x = 1;
		y = 0;
		rt a;
	}
	ll d = exgcd(b, a%b, x, y);
	ll temp = x;
	x = y;
	y = temp - a / b*y;
	rt d;
}

ll quickpow(ll x, ll n)
{
	ll t = x;
	ll ans = 1;
	while (n)
	{
		if (n & 1)ans *= t;
		n /= 2;
		t = t*t;
	}
	rt ans;
}

int main()
{
	//fr;
	detie; 
	ll a, b, c, k;
	while (cin >> a >> b >> c >> k)
	{
		if (a == 0 && b == 0 && c == 0 && k == 0)
			break;
		k = quickpow(2, k);
		ll m = gcd(c, k);//神特么c可能为零,这特么的顺序还很重要。。。
		if ((b - a) % m != 0)
		{
			cout << "FOREVER" << endl;
			continue;
		}
		ll x, y;
		exgcd(c, k, x, y);
		x = (b - a) / m*x;
		x = (x % (k / m) + k / m) % (k / m);
		cout << x << endl;
	}
	rt 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值