I'm trying to write a program that prints the factorial of a number:
#include <iostream>
using namespace std;
int main() {
int ans,fact=1, number;
cin>>number;
for (int i=1; i<=number; i++) {
fact = fact*i;
}
ans = fact%998244353;
cout <<ans<<endl;
return 0;
}
When I try to input the number 250, the program returns 0, but when I try to print a smaller number like 4, it returns the right number. Does anyone know why this occurs and how to fix this? Thanks.
Some hints for doing math in a finite field or ring while avoiding overflow.
Mathematically is true that:
(a*b)%c == ((a%c)*(b%c))%c
and also:
(a+b)%c == ((a%c)+(b%c))%c
But in the case a*b or a+b will overflow, you have to use the righthand expression because it is less likely to overflow.
Related
This particular Code was made on Dcoder on Android...
My question is,How am I still able to execute it if my input for n is less than 6..(Condition i>=6 is not fulfilled for the for loop right..)Also using this code I always get the answer as 1,2,3,5,8... and the number of terms printed is always more than the input of n..
Also I tried putting i<=0 but I get the same results...
#include <iostream>
using namespace std;
int a=0,b=1,x,i,n;
int main()
{
cout<<"This Program Gives You The List Of First 'n' Fibonacci Numbers:"<<endl
<<"Enter The Value Of 'n':"<<endl;
cin>>n;
if(n<1)
{
cout<<"Invalid Input"<<endl<<"Please Restart This Program And Enter A Natural Number."<<endl;
}
else
{
cout<<"The First "<<n<<" Fibonacci Numbers Are:"<<endl;
for(i;i>=6,i<=n;i++)
{
x=a+b;
a=b;
b=x;
cout<<x<<endl;
}
}
return 0;
}
But surprisingly the code below works..Why? And What is the fundamental difference between the two except that I intentionally print 0 and 1 in the second code...?Also I didn't find any difference when I used post increment and pre increment in my For Loop..Why?Also It would be really helpful to get some examples which behave differently with post and pre increment...
#include <iostream>
using namespace std;
int a=0,b=1,x,i,n;
int main()
{
cout<<"This Program Gives You The List Of First 'n' Fibonacci Numbers:"<<endl
<<"Enter The Value Of 'n':"<<endl;
cin>>n;
if(n<1)
{
cout<<"Invalid Input"<<endl<<"Please Restart This Program And Enter A Natural Number."<<endl;
}
else
{
cout<<"The First "<<n<<" Fibonacci Numbers Are:"<<endl;
cout<<"0"<<endl<<"1"<<endl;
for(i;i>=0,i<=n-2;i++)
{
x=a+b;
a=b;
b=x;
cout<<x<<endl;
}
}
return 0;
}
Your use of the comma operator is a problem and is leading you to believe that the condition is actually enforced.
This statement
i>=6,i<=n;
ignores the result (false if n==6) from i>=6, despite evaluating it and then proceeds to check if i<=n because that's how the comma(,) operator works in this context. Thus your loop still prints values when n is <=6. What you are looking for is
i>=6 && i<=n;
The && is the Logical AND operator which means that both the conditions need to be true for the statement to be true (and doesn't discard the Left Hand Side condition obviously).
As for why that loop runs for 7 times (one more than n if n is 6) that's because your loop essentially becomes:
for(i = 0; i <= 6; i++)
which shall run 7 times, starting from 0.
The same thing happens with your second piece of code, only this time that loop is essentially
for(i = 0; i<= n- 2;i++)
So, for a value of n as 6, you would have 5 iterations, which is what you see, i.e. the 5 terms after 0 and 1
This Program Gives You The List Of First 'n' Fibonacci Numbers:
Enter The Value Of 'n':
The First 6 Fibonacci Numbers Are:
0
1
1
2
3
5
8
This is my code for finding prime numbers between two integers. It compiles alright but giving a runtime error SIGXFSZ on codechef.
#include <bits/stdc++.h>
using namespace std;
int main() {
long long n,m;
int t;
cin>>t;
while(t--)
{
cin>>m>>n;
for(long long j=m;j<=n;j++)
for(long long i=2;i<=sqrt(j);i++)
if(j%i==0)
break;
else cout<<j<<"\n";
cout<<"\n";
}
return 0;
}
Seems that you are wrong on logic.
According to my understanding, you are supposed to print the prime numbers between two numbers.
But your code has logical errors.
1) Code doesn't consider 2 and 3 as prime numbers.
Say, m = 1, n = 10. For j = 2, 3, the inner loop won't execute even for the single time. Hence, the output won't be shown to be user.
2) else cout<<j<<"\n"; statement is placed incorrectly as it will lead to prime numbers getting printed multiple times and some composite numbers also.
Example:
For j = 11, this code will print 11 twice (for i = 2, 3).
For j = 15, this code will print 15 once (for i = 2) though it is a composite number.
You've underexplained your problem and underwritten your code. Your program takes two separate inputs: first, the number of trials to perform; second, two numbers indicating the start and stop of an individual trial.
Your code logic is incorrect and incomplete. If you were to use braces consistently, this might be clear. The innermost loop needs to fail on non- prime but only it's failure to break signals a prime, so there can't be one unless the loop completes. The location where you declare a prime is incorrect. To properly deal with this situation requires some sort of flag variable or other fix to emulate labelled loops:
int main() {
int trials;
cin >> trials;
while (trials--)
{
long long start, stop;
cin >> start >> stop;
for (long long number = start; number <= stop; number++)
{
if (number < 2 || (number % 2 == 0 && number != 2))
{
continue;
}
bool prime = true;
for (long long odd = 3; odd * odd <= number; odd += 2)
{
if (number % odd == 0)
{
prime = false;
break;
}
}
if (prime)
{
cout << number << "\n";
}
}
}
return 0;
}
The code takes the approach that it's simplest to deal with even numbers and two as a special case and focus on looping over the odd numbers.
This is basically "exceeded file size", which means that the output file is having size larger than the allowed size.
Please do check the output file size of your program.
Can u give me some help?I'm beginner and I dont know what's wrong with my program.It generates me all numbers to n not just prime numbers. why?
#include <iostream>
using namespace std;
int main()
{
unsigned int i,n,d;
bool prim;
cout<<"n=";
cin>>n;
for(i=2;i<=n;i=i+1)
{
prim=true;
for(d=2;d<=i/2;d=d+1)
if(i%d==0)
{
prim=false;
break;
}
(prim);
cout<<i<<",";
}
return 0;
}
Because (prim) is not the same as:
if (prim) {
cout << i << ",";
}
On a side note:
d=d+1 and i=i+1 can just be d++ and i++
You can declare variables inside the loops like: for (int i = 0;
Instead of (prim); use if(prim). The rest of your code is correct.
#include <iostream>
using namespace std;
int main()
{
unsigned int i,n,d;
bool prim;
cout<<"n=";
cin>>n;
for(i=2;i<=n;i=i+1)
{
prim=true;
for(d=2;d<=i/2;d=d+1)
if(i%d==0)
{
prim=false;
break;
}
if(prim)
cout<<i<<", ";
}
return 0;
}
Your condition for printing is not correct.
(prim);cout<<i<<",";
should be
if(prim) cout<<i<<",";
Note that your logic prints primes <= n, not the first n prime numbers.
You missed off the if:
if (prim) cout << i << ',';
The if statement could be reduced a little bit:
prim && cout<<i<<",";
This is because of the shortcut evaluation of logical expressions. So cout will only be evaluated if prime is true. If it is false, cout will be not evaluated as the expression is false anyway.
Minor comment: The divisor (d) may be increased till floor(sqr(i)), not till i/2 (more effective). Variable i may be started from 3 and increased by 2 as all even numbers are not prime (except 2, it can be printed without counting...).
I'm a total beginner in C++ and today I thought I'd write myself a small program that converts a decimal number to binary. The code looked something like this:
#include <iostream>
void binaryConvert(int);
int main() {
using namespace std;
cout << "Enter decimal number for conversion:" << endl;
int dec;
cin >> dec;
binaryConvert(dec);
}
void binaryConvert(int number) {
using namespace std;
while(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin;
}
}
Logically, this program would print the binary the other way around. I spent a long time trying to figure out how to invert the order of the binary digits so that the binary number would appear the right way around when I came across this piece of code:
void binaryConvert(int number) {
using namespace std;
if(number > 0) {
int bin = number % 2;
number /= 2;
binaryConvert(number);
cout << bin;
}
}
I know its probably a stupid question (I'm an absolute beginner), but I can't figure out why this code prints the bits in the correct order. Also, how come the bits actually get printed if the function gets called again before cout even gets executed?
Basically because "cout" is called after "binaryConvert". It's like putting all the bits in a stack and after that printing them.
It utilizes recursion, the bin at the end will not be printed until the base case is hit (number <= 0) and then it will go up the stack trace.
This function is a recursive one. It is calling itself recursively to print the least significant digits first, before printing out the most significant ones.
int num;
string BinaryRepresentation="";
cout<<"Input:";
cin>>num;
string newstring= "";
bool h;
h = true;
while(h){
BinaryRepresentation += boost::lexical_cast<std::string>( num % 2 );
num = num / 2;
if ( num < 1){
h = false;
}
}
for ( int i = BinaryRepresentation.size() - 1; i >= 0; i--){
newstring += BinaryRepresentation[i];
}
cout<< "Binary Representation: " << newstring <<endl;
}
Mainly the idea of the program is to find the reminder of the number and divide the number by 2 and and keep on repeating the same procedure until the number becomes 0. The you need to reverse the string in order to get the binary equivalent of the entered number.
As you have correctly mentioned your program inverted the binary as it gave the output.
To put the binary in the correct order to The second code starts giving output only once the final bit is obtained. The order of output is bin to the bin and hence we obtain the desired output. The following code may help your understanding further: http://ideone.com/Qm0m7L
void binaryConvert(int number) {
if(number > 0) {
int bin = number % 2;
number /= 2;
cout << bin<<" one"<<endl;
binaryConvert(number);
cout << bin<<" two"<<endl;
}
}
The output obtained is:
0 one
0 one
0 one
1 one
1 two
0 two
0 two
0 two
The output that precedes " one" is what your program would have given.
I hope you understand the difference.
While I was searching online to convert from decimal to binary, didn't find a simple and an understandable solution. So I wrote a program on my own.
Here it goes.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void dtobin(int n)
{
ostringstream oss;
string st="";
if(n<0)
{
cout<<"Number is negative";
return;
}
int r;
while(n!=1)
{
r=n%2;
oss<<st<<r;
n/=2;
}
oss<<st<<1;
st=oss.str();
cout<<st;
//To reverse the string
int len=st.length();
int j=len-1;
char x;
for(int i=0;i<=len/2-1;i++)
{
x=st[i];
st[i]=st[j];
st[j]=x;
--j;
}
cout<<endl<<st;
}
int main()
{
int n;
cout<<"ENTER THE NUMBER";
cin>>n;
dtobin(n);
return 0;
}
I am working on solving Euler project 3:
Description: The prime factors of 13195 are 5, 7, 13 and 29.
What is the largest prime factor of the number 600851475143 ?
This is my code to generate the answer. However I need an integer type to hold 600851475143. When I compile this on GCC on a Mac I get:
integer constant is too large for ‘long’ type".
I expect long long could easily hold this number. I also tried making it unsigned. Why doesn't my code hold that small number and what can I do to make it work?
#include <iostream>
#include <vector>
using namespace std;
static bool IsPrimeFactor(int numToTest,int testNum,vector<int> factors)
{
if(numToTest%testNum==0) // is it a factor?
{
// see if it is a prime factor
for(unsigned int i=0; i < factors.size(); i++)
{
if(testNum%factors[i]==0) // see if this factor
{ //is divisble by one we have already
return false;
}
}
return true;
}
return false;
}
int main() {
unsigned long long numToTest=600851475143;
unsigned int testNum=2; // 0 and 1 are assumed
vector<int> factors;
while(testNum<numToTest) // don't go higher than the max num
{
if(IsPrimeFactor(numToTest,testNum,factors)) // is it a factor?
{
factors.push_back(testNum); // got through prime factors
} // and none divided it
testNum++;
}
for(unsigned int i=0; i < factors.size(); i++)
{
cout << "factor " <<factors[i] << endl;
}
cout<<"Highest factor: " << factors[factors.size()-1]<<endl;
return 0;
}
Check this question. You have to specify your literal like this:
600851475143LL
As #Space_C0wb0y said, you need to specify a suffix for the literal.
Also, you're going to have a problem with your IsPrimeFactor function - the parameters are ints, but as you've already discovered, an int or even a long is not big enough to store the number you'll be passing in repeatedly...