How to find sum from 1 to 1 million in C? I tried using unsigned long long data type(my code below) but that prints 500,000,000,000. Correct value is 500,000,500,000.
unsigned long long sum = 0;
for(int i=0;i<1000000;i++)
sum += (unsigned long long)i;
printf("%llu",sum);
This should leave you with the correct answer. In your example you were finding the sum of 0 to 999,999. I also removed the needless casting for you.
unsigned long long sum = 0;
for (unsigned long long i = 1; i <= 1000000; i++) sum += i;
printf("%llu", sum);
The efficiency of the naive approach is terrible ! You should use the property that the sum of the integers from 0 to n is n(n+1)/2.
You sum up all numbers from 0 to 999999. Your result is some Kinde of strange.
With this you should get the correct one:
unsigned long long sum=0;
for(unsigned long long i=1;i<=1000000;i++){
sum+=i;
}
Related
#include <stdio.h>
int main() {
unsigned long int sum = 0LL;
long i;
for (i = 0LL; i < 100000000; i++) {
sum = sum + i;
}
printf("%i", sum);
}
that's all of my code, and I am curious why it prints 887459712 instead of 4999999950000000, and how to fix this
Your sum is declared unsigned long int, which is big enough for your expected result.The problem is not overflow.
The problem is your printf statement is wrong.
You told it to print a "normal" sized int with %i, which only goes up to about 4.2 billion.
You should tell printf to print an unsigned long int, using %llu
It should be:
printf("%llu", sum);
IDEOne Link
Results
Success #stdin #stdout 0s 5376KB
4999999950000000
Hey everyone of Stack Overflow!
So I am stuck on this prompt:
"Use a loop to determine the value of n that will produce the largest n! value that could be stored in an unsigned short variable. Print out the maximum value for an unsigned short variable, the value of n that will produce the largest n! that is less than or equal to the maximum value for an unsigned short variable. NOTE: The constant USHRT_MAX contained in limits.h provides the maximum value for an unsigned short variable."
I'm guessing, for the above prompt, that it addresses why when I enter an integer such as 34 into the program, I get 0 as the output for the factorial of 34.
I have already made the code for determining the n! value when n is entered so far, but this new part has me confused.
I don't think this will help, but here is the code I have before this prompt:
#include <stdio.h>
unsigned long Factorial(unsigned int n);
int main(void)
{
int num[11],i=0,factorials[11];
printf("Please enter up to 10 integers (q to quit): ");
//Ask for integers until a 'q' is entered and store integer values entered into array 'num'
while (scanf("%u",&num[i]))
{
//Store the factorial of integers entered into array 'factorials'
factorials[i]=Factorial(num[i]);
//Print numbers out in a two column table
printf("%5u %9u\n",num[i],factorials[i]);
i++;
}
return 0;
}
//Calculates the factorial of 'n'
unsigned long Factorial(unsigned int n)
{
int nFactorial,i=1;
nFactorial=n;
while (i<n)
{
nFactorial=nFactorial*i;
i++;
}
n=nFactorial;
}
Anyways, if anyone can help out, I'd greatly appreciate it! I know this sounds like a tall order of a question, so even a pointer would help heaps!
Thanks anyone!
Cheers, Will.
EDIT: I apologize in advance if my code is difficult to read, I'm working on making it better
EDIT:
I came up with this to answer the prompt so far, but it doesn't seem right. The output value is 8...
//Detemine largest max value of n
for (i=0;Factorial(i)<=USHRT_MAX;i++);
printf("The max value for an unsigned short is %u\n Max value of n: %u\n",USHRT_MAX,i-1);
return 0;
Since you're using a short, you can store the factorial sum in a larger type like unsigned long int.
int main(void)
{
unsigned long int sum = 1;
unsigned int n;
for( n = 1; sum < USHRT_MAX; n++ ) {
sum *=n;
}
printf("%lu\n", sum);
printf("%u\n", n);
}
This is kind of cheating as there's no guarantee a long int will be larger than a short, but it's really likely. You can mitigate that by verifying.
assert( sizeof(unsigned short) < sizeof(unsigned long int) );
The non-cheating way is to check if you're about to overflow. You're gonna want to do this, but you can't.
USHRT_MAX >= sum * n
sum * n will overflow. Instead, divide both sides by n and check that.
USHRT_MAX / n >= sum
That will stop just before sum *= n would overflow. We can verify by plugging in some numbers. USHRT_MAX = 23, n = 4 and sum = 6...
23 / 4 >= 6
5 >= 6
Note that this is integer division, so it's truncated. That's fine for our purposes.
#include <stdio.h>
#include <limits.h>
int main(void)
{
unsigned short sum = 1;
unsigned int n;
for( n = 1; (USHRT_MAX / n) >= sum; n++ ) {
sum *=n;
}
// We went one too far
n--;
printf("%u\n", sum);
printf("%u\n", n);
}
I am using 64 bit operating system ,then also i am not able to print 46th fibonacci number correctly which is less than 4 billion.
#include<cs50.h>
#include<stdio.h>
int main(void)
{
unsigned int n=50;
int array[n];
array[0]=0;
array[1]=1;
printf("%i\n",array[0]);
printf("%i\n",array[1]);
for(int i=2;i<n;i++)
{
array[i]=array[i-1]+array[i-2];
printf("%i\n",array[i]);
}
You have to use long long as your data type of the array. because You are going to store out-range numbers of the integer range.(-2,147,483,648 to 2,147,483,647)
And declaration of int i should be before the for loop.
#include<stdio.h>
int main(void)
{
int n=50;
long long array[n];
array[0]=0;
array[1]=1;
printf("%lli\n",array[0]);
printf("%lli\n",array[1]);
int i;
for(i=2;i<n;i++)
{
array[i]=array[i-1]+array[i-2];
printf("%lli\n",array[i]);
}
}
i am not able to print 46th fibonacci number correctly which is less than 4 billion.
You are most probably going out of range of an integer, which is from -4294967296 to 4294967295.
Change int array[n]; to long long array[n];
Also, the printf's should be changed from %i to %lli
Edit : On running the numbers, you get expected value of F(48) as 4807526976 which is out of range of an integer.
Using Rishikesh Raje's counting system (i.e. 1st Fibonacci is 1) where F(48) is 4807526976, then you weren't able to get F(47) 2971215073 because, as #kaylum commented, you used a signed integer array to hold your values which you need to change to unsigned, and well as change your printf statement to print an unsigned. This would allow you to reach the limit of 32 bit arithmetic:
#include <stdio.h>
#define LIMIT (50)
int main(void) {
unsigned int array[LIMIT] = {0, 1};
printf("%u\n", array[0]);
printf("%u\n", array[1]);
for (size_t i = 2; i < LIMIT; i++)
{
array[i] = array[i - 1] + array[i - 2];
printf("%u\n", array[i]);
}
return 0;
}
To get beyond 32 bits, you can switch to long, or long longs as Rishikesh Raje suggests, but work with unsigned variants if you want to reach the maximum result you can with a given number of bits.
Either Use an unsigned integer array or for more higher values use unsigned long long long array but you don't need an array to print fibonacci series you can simply do this:-
void main()
{
unsigned long long i=1, num1=1, num2=0;
printf("1 \n");
for(i; i<100 ; i++)
{
num1=num1+num2;
num2=num1-num2;
printf("%lli \n", num1);
}
getch();
}
I am writing a very basic program to print the range of an unsigned long long variable in C language (0 to ((2 ^ n) - 1) where n is the number of bits for the data type in any system (with C installed in it and according to the compiler). In my system, the size of a long long variable is 8 bytes.
I am using the following code:
#include<stdio.h>
#include<math.h>
int main()
{
unsigned long long n;
//n = pow(2, 63);
//n = (n * 2) - 1;
n = pow(2, 64) - 1;
printf("\nn: %llu\n", n);
return 0;
}
upon compiling, gcc gives me the following error:
Print_long_long_int.c:10:2: warning: overflow in implicit constant conversion [-Woverflow].
On executing it, I get the correct output of
n: 18446744073709551615
But, if I remove the single comments from the lines, and use them:
n = pow(2, 63);
n = (n * 2) - 1;
Instead of:
n = pow(2, 64) - 1;
It doesn't give me any such warning. And executes normally.
Why is this discrepancy happening?
Thanks!
When you are giving
pow(2,64) -1 ;
It exceeds the limit of unsigned long long. This is the reason you are getting that warning.
Range of unsigned long is 0 to 18,446,744,073,709,551,615
Result of pow(2,64) is 18446744073709551616.
Power should return an integer, and you're getting an unsigned long long. I just made a simple power function to handle unsigned long longs.
#include<stdio.h>
unsigned long long power(int base, int exponent)
{
unsigned long long n = 1;
int i;
for (i = 0; i < exponent ; i++)
n *= base;
return n;
}
int main()
{
unsigned long long n = power(2, 64) - 1;
printf("n: %llu\n", n);
return 0;
}
The nth term of the series is f(n).
f(n) = 1, when n=1
f(n)= ((n-1)*(8*(n–2)* 2+ 20)+4) , when n>1
P(n)=f(1)+f(2)+.....f(n)
1<=n<=10^9
for a given n we have to find P(n) modulo 10^9+7.
I solved the equation and finally getting the answer as
P(n)=(16n^3-18n^2+14n-12)/3
Problem comes when I implemented it in c++.
Given below the code tell me whats wrong with it and how to resolve it?
#include<stdio.h>
#define c 1000000007
int main()
{
long long int t,n,sum;
scanf("%lld",&t);
while(t--)
{
sum=0;
scanf("%lld",&n);
if(n==1)
printf("1\n");
else
{
sum=(((16*(((((n%c)*(n%c))%c)*(n%c))%c)%c)+14*(n%c))%c-(18*(((n%c)*(n%c))%c)%c+12)%c)/3;
sum++;
printf("%lld\n",sum);
}
}
return 0;
}
There are multiple issues in your code.
Problem 1:
An expression like long long b = ((a%c)*(a%c))%c; with a and b being long long
and c just a "plain number", ie. int, is still subject to int overflow, without
using the full capabilities of long long. The reason is the result of modulo:
long long = ((long long % int) * (long long % int)) % int;
long long = (int * int) % int;
long long = int % int; //overflow here
long long = int;
long long = long long; //expanding too late
//finished
As an example to check (http://ideone.com/kIyM7K):
#include <iostream>
using namespace std;
int main() {
int i = 1000000;
long long ll = 1000000;
cout<< ((999999%i)*(999999%i)*(999999%i)) << endl;
cout<< ((999999%ll)*(999999%ll)*(999999%ll)) << endl;
return 0;
}
In your code, 1000000007 is not a long long ...
Use 1000000007ULL to treat is as unsigned long long
Problem 2:
You´re using (or at least "used", before the edits) %lld in printf and scanf
for unsigned long long, which is %llu. %lld would be a signed long long
Problem 3:
P(n) purely mathematical and without modulo is positive for every natural number n>=1.
But P(0) is negative, and more important: The four parts of your equation modul´t
and the added/subtracted together could result in a negative number, which is congruent
to the positive expected result, but C doesn´t know that.
So, use signed instead of unsigned, and after the whole calculation, check
if the result is <0 and add c to it to make it >0
Problem 4:
A problem with parenthesis and operator precedence somewhere in your long formula.
A working example, but without the loops and input:
#include<stdio.h>
int main()
{
signed long long n, res, c;
n = 2456ULL;
c = 1000000007ULL;
signed long long part1 = (16*(((n%c)*(n%c)%c)*(n%c)%c))%c;
signed long long part2 = (18*((n%c)*(n%c)%c))%c;
signed long long part3 = (14*(n%c))%c;
res = ((part1 - part2 + part3 - 12)%c)/3 + 1;
printf("%lld\n", res);
return 0;
}
Not a problem:
You don´t need a special check for n=1, because the
whole calculation will result in 1 anyways.