如何解决具有模数的周期函数
给出 F(0)= 0,F(1)= 1,F(2)= 2,F(3)= 3 和 F(n)=(F( n-1)-F(n-3)+ F(n-4))%m 。任务是实现一种有效的算法来计算 F(n) 其中n是二进制表示形式中给出的 10 ^ 5 位号, m
#include<bits/stdc++.h>
using namespace std;
int main(int argc,char const *argv[]) {
/* input binary number from the file i.txt.*/
std::ifstream t("input.txt");
std::stringstream buffer;
buffer << t.rdbuf();
string s=buffer.str();
/* Given function forms a periodic sequece which reapeats ifself after a period of 6 irrespective of the value of m */
vector<int> v{0,1,2,3,1}; //vector holding the value corresponding to F[0],F[1],F[2],F[3],F[4],F[5].
int offset = s.length()%16; // This line is to find the number of bits short in the input length to make it a 16 multiple.
string s_dash="0";
for(int j=1;j<(16-offset);++j){ // This appends the 16-offset number of zeroes to make input length multiple of 16.
s_dash.append("0"); // TC: O(1)
}
s_dash.append(s);
long long i=0;
long long rem=0b0;
long multiplier=0b10000000000000000; // multiplier corresponds to 2^16. As we reading input data as chuck of 16 bytes. So required in modulus calculation.
while(i<s_dash.length()) // for calculation of modulus when input number is divided by 6
{
string ss=s_dash.substr(i,16); //reads 16 bits from string
rem=(rem*multiplier + stoll(ss,nullptr,2))%6;
i=i+16;
}
cout<<"Remainder : "<<rem<<endl;
cout<<"For given n,F(n)="<<v[rem]; // prints the F(n) value based on the remainder.
}
我想出了这个解决方案作为代码。但是找不到为什么这个问题曾经需要 m 值吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。