Related
When I try to write a small program in C language that is intended to generate a 4-digit integer for which every digit is distinct and nonzero, the returned value is always in pattern like 1abc: the first digit seems to always be 1, and sometimes the returned value will be more than 4-digit like 56127254. Could anyone help me look into this? Thank you very much in advance.
So basically the program includes two functions, int isvalid(int n) and int choose_N(void).
isValid return 1 if the integer consists of exactly 4 decimal digits, and all these digits are nonzero and distinct, and 0 otherwise.
And int choose_N(void) generates an integer that is 4-digit and all the digits are distinct and nonzero.
Here is my code:
#define N_DIGITS 4
....
....//the main function
int isvalid(int n){
int i, x; int check[N_DIGITS]={0};
for(i=1;i<=N_DIGITS;i++){ //check whether all digits are nonzero
if((check[i-1]=n%10)==0){
return 0;
}
n /= 10;
}
for(i=0;i<N_DIGITS-1;i++){ // check whether all digits are distinct
for(x=i+1;x<N_DIGITS;x++){
if(check[i]==check[x])
return 0;
}
}
return 1;
}
int choose_N(void){
int i; int number=0;
while(!isvalid(number)){
for(i=0;i<N_DIGITS;i++){
srand(time(0));
number += ((10^i)*(rand()%10));
}
}
return number;
}
For srand(time(0));, I have tried various alternatives like srand(time(0)+i); or put this statement out of while loop, but those attempts seemingly did not work and still the returned value of choose_Nstill showed the werid pattern that I described.
your choose_N method has several issues:
First, if the number isn't valid, you're not resetting it to 0, so it just grows and grows.
Second, srand(time(0)) is not necessary within the loop (and could yield the same result for several iterations), just do it at program start (srand() — why call it only once?)
Third and biggest mistake: 10 ^ i is 10 xor i, not 10**i. You can use an aux value and multiply by 10 in your loop. Since number of digits is low, no risk of overflow
minor remark: you want to pass in the loop at least once, so use a do/while construct instead, so you don't have to force the first while test.
I'm trying to fix your code:
int choose_N(void){
int i, number;
do
{
number = 0;
int p = 1;
for(i=0;i<N_DIGITS;i++)
{
number += p*(rand()%10);
p *= 10;
}
} while(!isvalid(number));
return number;
}
While #Jean-François-Fabre answer is the right one, it is not optimal algorithm. Optimal algorithm in such case would be using FIsher-Yates-Knuth shuffle and Durstenfeld's implementation.
Shuffling right array will produce numbers which are automatically valid, basically no need for isvalid(n) anymore.
Code
// Swap selected by index digit and last one. Return last one
int
swap_array(int digits[], int idx, int last) {
if (idx != last) { // do actual swap
int tmp = digits[last];
digits[last] = digits[idx];
digits[idx] = tmp;
}
return digits[last];
}
int
choose_N_Fisher_Yates_Knuth() {
int digits[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int r = 0;
for (int k = 0; k != N_DIGITS; ++k) {
int idx = rand() % (9 - k);
int n = swap_array(digits, idx, (9 - k) - 1);
r = r * 10 + n;
}
return r;
}
int
main() {
srand(12345);
int r, v;
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
r = choose_N_Fisher_Yates_Knuth();
v = isvalid(r);
printf("%d %d\n", r, v);
return 0;
}
Output
7514 1
6932 1
3518 1
5917 1
I have to write a program that takes in two positive integers, start and end, where (1 < start < end). Then the program would look within this range [start, end] and count the number of powers of 3.
So, for example, if start is 2 and end is 10, the output would be 2. (as 3 and 9 are powers of 3).
Below is my code:
#include <stdio.h>
#include <math.h>
int main(void) {
int start, end, i, count = 0;
printf("Enter start and end: ");
scanf("%d %d", &start, &end);
for (i = start; i <= end; i++) {
if ((log(i) / log(3)) == floor((log(i) / log(3)))) {
printf("%d\n", i);
count++;
}
}
printf("Answer = %d\n", count);
return 0;
}
But, when I tried to run one of the test cases [3, 1000], the output is 5, when it should be 6.
3
9
27
81
729
Answer = 5
The number 243 is missing. Is there something wrong with my code?
The problem is you are using exact comparison of floating point numbers. Specifically, here:
if ((log(i)/log(3)) == floor((log(i)/log(3))))
Since log() and floor() return double, you're comparing without any tolerance two values which cannot be compared that way.
How should I do floating point comparison?
Your immediate problem has to do with the imprecision of floating point numbers, something that is generally well documented on the net, including various methods useful in fixing that problem.
However, I'm not actually going to bother referring you to them because the use of floating point is totally unnecessary here. There's a much more efficient way of doing this that involves only integers.
Rather than going through numbers in your range looking for powers of three using floating point operations, you would be better off going through powers of three (using just integer multiplication) looking for numbers in your range.
In pseudo-code, that would go something like:
powerOfThree = 1
while powerOfThree <= endRange:
if powerOfThree >= startRange:
print powerOfThree
powerOfThree = powerOfThree * 3
You could even make it more efficient by selecting a more suitable starting value for powerOfThree but, since there are only 40-odd powers of three in a 64 bit number, that's probably a waste of time.
When converting from pseudo-code to the more concrete C, you unfortunately come across the limitations of the datatypes in that language, specifically the fact that multiplication may result in overflow.
There are various ways you can avoid this this such as detecting that it's about to happen and exiting the loop early.
Given below is the function that you need, one which handles this issue, along with some test code which can be used for validating it.
#include <stdio.h>
#include <limits.h>
// I hate typing :-)
typedef unsigned long ULONG;
typedef unsigned int UINT;
static UINT countPowersOfThreeBetween (ULONG low, ULONG high) {
// Catch invalid params, just exit with zero.
if (low > high) return 0;
// Go through all powers of three.
ULONG powerOfThree = 1;
UINT count = 0;
do {
// If within your range, count it.
if ((powerOfThree >= low) && (powerOfThree <= high)) {
count++;
// printf ("DEBUG: got %lu\n", powerOfThree);
}
// Early exit if about to overflow.
if (ULONG_MAX / powerOfThree < 3) break;
// Advance to next power and continue if within range.
powerOfThree *= 3;
} while (powerOfThree <= high);
// Notify caller of count.
return count;
}
// Test function to make test suite easier.
static void testRange (ULONG low, ULONG high) {
UINT count = countPowersOfThreeBetween (low, high);
printf ("In range %lu..%lu, found %u occurrences\n", low, high, count);
}
// Test suite, add whatever you need.
int main (void) {
testRange (1000, 10);
testRange (0, 0);
testRange (9, 9);
testRange (3, 1000);
testRange (0, ULONG_MAX);
testRange (ULONG_MAX, ULONG_MAX);
return 0;
}
As you will see from the output, this gives the correct counts for various ranges:
In range 1000..10, found 0 occurrences
In range 0..0, found 0 occurrences
In range 9..9, found 1 occurrences
In range 3..1000, found 6 occurrences
In range 0..18446744073709551615, found 41 occurrences
In range 18446744073709551615..18446744073709551615, found 0 occurrences
And, if you uncomment the printf line in countPowersOfThreeBetween(), you'll also see the actual values detected.
Before choosing floating point types in the future, I strongly recommend you read this article entitled "What every computer scientist should know about floating-point arithmetic", by David Goldberg. It explains your problem(s) nicely, much better than I could have.
You don't actually need floating point (or negative integer) types here, so they should be avoided. Form your powers by multiplication, rather than addition:
#include <assert.h>
#include <limits.h>
#include <stdio.h>
int main(void){
unsigned int start, end, i, count = 0;
printf("Enter start and end: ");
int x = scanf("%u %u", &start, &end);
assert(x == 2); // XXX: INSERT PROPER ERROR HANDLING!
// find the first power greater than or equal to start
for (i = 1; i < start && UINT_MAX / 3 >= i; i *= 3);
// ... then count each one less than or equal to end
while (i <= end && UINT_MAX / 3 >= i) {
printf("%u\n", i);
i *= 3;
count++;
}
printf("Answer = %u\n", count);
}
Your problem is round-off error while float calculating in computer, the result of log(243)/log(3) is not exactly log3(243), where computer store approximate value of it. eg, in my 32bit computer, it is 4.99999999999999911182.
However, you have two ways to solve it,
use integer calculation instead of float.
simple mathematical transformation.
number of powers of 3 in [start, end] is equivalent to floor(log3(end)-log3(start))+1, wrote in c is
printf("answer:%d\n", (int)((log(1000)-log(3))/log(3))+1);
complete code:
#include <stdio.h>
#include <math.h>
int pow3(int n) {
int ret = 1;
while(n--) {
ret *= 3;
}
return ret;
}
int main() {
int a, start, end, answer;
scanf("%d%d", &start, &end);
a = (int)(log(start+0.5)/log(3));
//printf("%d,%d,%d\n", a, pow3(a), start);
if(start == end) answer = (start == pow3(a));
else answer = (int)((log(end+0.5)-log(start))/log(3))+1;
printf("answer = %d\n", answer);
}
Result:
Input[0]: 2 10
Output[0]: 2
Input[1]: 1 3
Output[1]: 2
Input[2]: 3 1000
Output[2]:6
Your program fails because of floating point precision issues.
Use integer arithmetics instead:
#include <limits.h>
#include <stdio.h>
int main(void) {
unsigned int start, end, i, count;
printf("Enter start and end: ");
if (scanf("%u %u", &start, &end) == 2) {
for (i = 1, count = 0; i <= end && i <= UINT_MAX / 3; i *= 3) {
if (i >= start) {
printf("%u\n", i);
count++;
}
}
printf("Answer = %u\n", count);
}
return 0;
}
A direct solution with floating point arithmetics is possible too:
#include <math.h>
#include <stdio.h>
int main(void) {
unsigned int start, end, count = 0;
printf("Enter start and end: ");
if (scanf("%u %u", &start, &end) == 2) {
if (end > 0 && end >= start) {
int start3 = (start <= 1) ? 0 : (int)(log(start - 0.5) / log(3));
int end3 = (int)(log(end + 0.5) / log(3));
count = end3 - start3;
}
printf("Answer = %u\n", count);
}
return 0;
}
Hello guys i am trying to implement a program which is finding the happy numbers were between two numbers A and B.
Summing the squares of all the digits of the number, we replace the number with the outcome, and repeat the process. If after some steps the result is equal to 1 (and stay there), then we say that the number N is **<happy>**. Conversely, if the process is repeated indefinitely without ever showing the number 1, then we say that the number N is **<sad>**.
For example, the number 7 is happy because the procedure described above leads to the following steps: 7, 49, 97, 130, 10, 1, 1, 1 ... Conversely, the number 42 is sad because the process leads to a infinite sequence 42, 20, 4, 16, 37, 58, 89, 145, 42, 20, 4, 16, 37 ...
I try this right down but i am getting either segm faults or no results.
Thanks in advance.
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void happy( char * A, int n);
int numPlaces (long n);
int main(void)
{
long A,B;
int npA;
char *Ap;
printf("Give 2 Numbers\n");
scanf("%li %li",&A,&B);
npA = numPlaces(A);
Ap = malloc(npA);
printf("%ld %d\n",A,npA);
//Search for happy numbers from A to B
do{
sprintf(Ap, "%ld", A);
happy(Ap,npA);
A++;
if ( npA < numPlaces(A) )
{
npA++;
Ap = realloc(Ap, npA);
}
}while( A <= B);
}
//Finds happy numbers
void happy( char * A, int n)
{
//Basic Condition
if ( n == 1)
{
if (A[0] == 1 || A[0] == 7)
printf("%c\n",A[0]);
printf("%s\n",A);
return;
}
long sum = 0 ;
char * sumA;
int nsum;
int Ai;
//Sum the squares of the current number
for(int i = 0 ; i < n;i++)
{
Ai = atoi(&A[i]);
sum = sum + (Ai*Ai);
}
nsum = numPlaces (sum);
sumA = malloc(nsum);
sprintf(sumA, "%li", sum);
happy(sumA,nsum);
free(sumA);
}
//Count digits of a number
int numPlaces (long n)
{
if (n < 0) return 0;
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
Thanks for your time.
by the definition of your program sad numbers will cause your program to run forever
Conversely, if the process is repeated indefinitely
You need to add a stopping condition, like if I have looped for 1000 times, or if you hit a well known non terminating number (like 4) (is there a definite list of these? I dont know)
I find this solution tested and working..
Thanks for your time and I am sorry for my vagueness.
Every advice about this solution would be welcome
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void happy( char * A, int n);
int numPlaces (long n);
int happynum = 0;
int main(void)
{
long A,B;
int npA;
char *Ap;
printf("Give 2 Numbers\n");
scanf("%li %li",&A,&B);
npA = numPlaces(A);
Ap = malloc(npA);
//Search for happy numbers from A to B
do{
sprintf(Ap, "%ld", A);
happy(Ap,npA);
if (happynum ==1)
printf("%s\n",Ap);
A++;
if ( npA < numPlaces(A) )
{
npA++;
Ap = realloc(Ap, npA);
}
}while( A <= B);
}
//Finds happy numbers
void happy( char * A, int n)
{
//Basic Condition
if ( n == 1)
{
if (A[0] == '3' || A[0] == '6' || A[0] == '9')
{
happynum = 0;
}
else
{
happynum = 1;
}
return;
}
long sum = 0;
char * sumA;
int nsum;
int Ai;
//Sum the squares of the current number
for(int i = 0 ; i < n;i++)
{
Ai = (int)(A[i]-48);
sum = sum + (Ai*Ai);
}
nsum = numPlaces (sum);
sumA = malloc(nsum);
sprintf(sumA, "%li", sum);
happy(sumA,nsum);
free(sumA);
}
//Count digits of a number
int numPlaces (long n)
{
if (n < 0) return 0;
if (n < 10) return 1;
return 1 + numPlaces (n / 10);
}
Your code uses some questionable practices. Yoe may be misguided because you are concerned about performance and memory usage.
When you allocate memory for the string, you forget to allocate one character for the null terminator. But you shouldn't be allocating, re-allocating and freeing constantly anyway. Dynamic memory allocation is expensive compared to your other operations.
Your limits are long, which may be a 32-bit or 64-bit signed integer, depending on your platform. The maximum number that can be represented with e 64-bit signed integer is 9,223,372,036,854,775,807. This is a number with 19 digits. Add one for the null terminator and one for a possible minus sign, so that overflow won't hurt, you and use a buffer of 21 chars on the stack.
You probably shouldn't be using strings inthe first place. Use the basic code to extract the digits: Split off the digit by taking the remainder of a division by 10. Then divide by 10 until you get zero. (And if you use strings with a fixed buffer size, as described above, you don't have to calculate the difits separately: sprintf returns the number of characters written to the string.
Your functions shouldn't be recursive. A loop is enough. As pm100 has noted, you need a termination criterion: You must keep track of the numbers that you have already visited. Each recursive call creates a new state; it is easier to keep an array, that can be repeatedly looked at in a loop. When you see a number that you have already seen (other than 1, of course), your number is sad.
Happy and sad numbers have this property that when your sum of squares is a number with a known happiness, the original number has this happiness, too. If you visit a known das number, the original number is sad. If you visit a known happy number, the original number is happy.
The limits of your ranges may ba large, but the sum of square digits is not large; it can be at most the number of digits times 81. In particular:
type max. number number of max. square sum dss
int 2,147,483,647 1,999,999,999 730
uint 4,294,967,295 3,999,999,999 738
long 9,223,372,036,854,775,807 8,999,999,999,999,999,999 1522
ulong 18,446,744,073,709,55,1616 9,999,999,999,999,999,999 1539
That means that when you take the sum of digit squares of an unsigned long, you will get a number that is smaller than 1540. Create an array of 1540 entries and mark all known happy numbers with 1. Then you can reduce your problem to taking the sum of digit squares once and then looking up the happiness of the number in this array.
(You can do the precalculation of the array once when you start the program.)
Say I have a multi-digit integer in C. I want to break it up into single-digit integers.
123 would turn into 1, 2, and 3.
How can I do this, especially if I don't know how many digits the integer has?
int value = 123;
while (value > 0) {
int digit = value % 10;
// do something with digit
value /= 10;
}
First, count the digits:
unsigned int count(unsigned int i) {
unsigned int ret=1;
while (i/=10) ret++;
return ret;
}
Then, you can store them in an array:
unsigned int num=123; //for example
unsigned int dig=count(num);
char arr[dig];
while (dig--) {
arr[dig]=num%10;
num/=10;
}
As a hint, getting the nth digit in the number is pretty easy; divide by 10 n times, then mod 10, or in C:
int nthdig(int n, int k){
while(n--)
k/=10;
return k%10;
}
The last digits of 123 is 123 % 10.
You can drop the last digit of 123 by doing 123/10 -- using integer division this will give you 12.
To answer your question about "how do I know how many digits you have" --
try doing it as described above and you will see how to know when to stop.
I think below piece of code will help....
temp = num;
while(temp)
{
temp=temp/10;
factor = factor*10;
}
printf("\n%d\n", factor);
printf("Each digits of given number are:\n");
while(factor>1)
{
factor = factor/10;
printf("%d\t",num/factor);
i++;
num = num % factor;
}
//Based on Tony's answer
#include <stdio.h>
int nthdig(int n, int k){
while(n--)
k/=10;
return k%10;
}
int main() {
int numberToSplit = 987;
printf("Hundreds = %i\n",nthdig(2, numberToSplit));
printf("Tens = %i\n",nthdig(1, numberToSplit));
printf("Units = %i\n",nthdig(0, numberToSplit));
}
This results in the following printout:
Hundreds = 9
Tens = 8
Units = 7
I made this based on the code from #asaelr:
typedef struct digitsArrayPlusNumber {
uint32_t *baseAddress;
uint32_t number;
} digitsArrayPlusNumber;
digitsArrayPlusNumber *splitDigits (uint32_t inValue) {
// based on code from asaelr#stackoverflow.com
uint32_t inputValue = inValue;
//Count digits
uint32_t theCount = 1;
while (inputValue /= 10)
theCount++;
// put in array
uint32_t *arr = malloc(sizeof(uint32_t) * theCount);
uint32_t dig = theCount;
while (dig--) {
arr[dig]=inValue % 10;
inValue /= 10;
// printf ("%d\n", arr[dig]);
}
digitsArrayPlusNumber *dandn = malloc (sizeof(digitsArrayPlusNumber));
dandn->baseAddress = arr;
dandn->number = theCount;
return dandn;
}
int main(int argc, const char * argv[]) {
for (int d = 0; d < splitDigits(12345678)->number; d++)
printf ("%u\n", (splitDigits(12345678)->baseAddress)[d]);
}
It works quite well, thanks!
You can use %10, which means the remainder if the number after you divided it. So 123 % 10 is 3, because the remainder is 3, substract the 3 from 123, then it is 120, then divide 120 with 10 which is 12. And do the same process.
we can use this program as a function with 3 arguments.Here in "while(a++<2)", 2 is the number of digits you need(can give as one argument)replace 2 with no of digits you need. Here we can use "z/=pow(10,6)" if we don't need last certain digits ,replace 6 by the no of digits you don't need(can give as another argument),and the third argument is the number you need to break.
int main(){
long signed c=0,z,a=0,b=1,d=1;
scanf("%ld",&z);
while(a++<2){
if(d++==1)
z/=pow(10,6);
c+=(z%10)*b;
z/=10;
b*=10;}
return c;}
You can divide and conquer but you have rewrite all of arithmetic libraries. I suggest using a multi-precision library https://gmplib.org But of course it is good practice
By starting with 1 and 2, the first 10 terms of Fibonacci Series will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
Find the sum of all the even-valued terms in the sequence which do not exceed 4 million.
Now, I got the idea for how to do this. But I'm confused about the data types to hold such big data. I'm getting weird results with int. :(
MORE: Its Project Euler 2nd question. But I can't get it. I get crazy values as answer. Can someone please post the ideal program?
EDIT: Here's what I wrote for just printing Fibonacci to screen. Bare Basic. My variable goes crazy even when I give 100 for the limit. Is my code wrong?
// Simple Program to print Fibonacci series in Console
#include <stdio.h>
int main() {
int x=1,y=2,sum=0,limit=0,i=0,temp=0;
printf("Enter Limit:");
scanf("%d",&limit);
if(limit==1)
printf("%d",x);
else if(limit>1) {
printf("%d %d",x,y);
if (limit>2) {
while (i<limit-2) {
temp=y;
sum=x+y;
x=temp;
y=sum;
printf(" %d",sum);
i++;
}
}
}
printf("\n");
return 0;
}
SOLVED: Actually, I managed to get the solution myself. Here's my program. It works.
#include <stdio.h>
int main() {
int x=1,y=2,sum,limit; //Here value of first 2 terms have been initialized as 1 and 2
int evensum=2; //Since in calculation, we omit 2 which is an even number
printf("Enter Limit: "); //Enter limit as 4000000 (4million) to get desired result
scanf("%d",&limit);
while( (x+y)<limit ) {
sum=x+y;
x=y;
y=sum;
if (sum%2==0)
evensum+=sum;
}
printf("%d \n",evensum);
return 0;
}
Since you only want up to four million, it's likely that int is not your problem.
It's quite possible that your program is buggy and that the data storage is just fine, so you should test your program on smaller values. For example, it's clear that the sum of the first three even terms is 44 (hint: every third term is even) so if you run your program with a cap of 50, then you should instantly get 44 back. Keep running small test cases to get confidence in the larger ones.
For security, use the 'long' data type; the C standard requires that to hold at least 4 billion, but on most machines, 'int' will also hold 4 billion.
enum { MAX_VALUE = 4000000 };
int sum = 0;
int f_n0 = 0;
int f_n1 = 1;
int f_n2;
while ((f_n2 = f_n0 + f_n1) < MAX_VALUE)
{
if (f_n2 % 2 == 0)
sum += f_n2;
f_n0 = f_n1;
f_n1 = f_n2;
}
printf("%d\n", sum);
I am not a programmer, but here's an adaptation to Leffler's code without the IF-criterion. It should work for MAX_VALUES above 2 (given there are no mistakes in programming syntax), based on a pattern I found in the even-only fibonacci series: 0,2,8,34,144,610,2584... so interestingly: f_n2 = 4*f_n1 + f_n0. This also means this program only needs 1/3rd of the calculations, since it doesn't even consider/calculate the odd fibonacci numbers.
enum { MAX_VALUE = 4000000 };
int sum = 2;
int f_n0 = 0;
int f_n1 = 2;
int f_n2 = 8;
while (f_n2 < MAX_VALUE)
{
sum += f_n2;
f_n0 = f_n1;
f_n1 = f_n2;
f_n2 = 4*f_n1 + f_n0;
}
printf("%d\n", sum);
Try changing this:
while (i<limit-2)
to this:
while (y<limit)
As written, your program is cycling until it gets to the 4 millionth Fibonacci number (i.e. when i gets to 4 million, though overflow obviously happens first). The loop should check to see when y (the larger Fibonacci number) becomes greater than 4 million.
Guys, I got the answer. I confirmed the result and int can handle it. Here's my program:
#include <stdio.h>
int main() {
int x=1,y=2,sum,limit; //Here value of first 2 terms have been initialized as 1 and 2
int evensum=2; //Since in calculation, we omit 2 which is an even number
printf("Enter Limit: "); //Enter limit as 4000000 (4million) to get desired result
scanf("%d",&limit);
while( (x+y)<limit ) {
sum=x+y;
x=y;
y=sum;
if (sum%2==0)
evensum+=sum;
}
printf("%d \n",evensum);
return 0;
}
Thx for all the replies and help. "Thinking on my feet" to the rescue :)
An amusing solution is to use the closed form for Fibonacci sequences and the closed form for geometric progressions. The end solution looks like this:
sum = ( (1-pow(phi_cb, N+1)) / (1-phi_cb) - (1-pow(onephi_cb,N+1)) / (1-onephi_cb)) / sqrt(5);
where
double phi = 0.5 + 0.5 * sqrt(5);
double phi_cb = pow(phi, 3.0);
double onephi_cb = pow(1.0 - phi, 3.0);
unsigned N = floor( log(4000000.0 * sqrt(5) + 0.5) / log(phi) );
N = N / 3;
with all the caveats regarding double to int-type conversions of course.
int is big enough for values in the millions on almost every modern system, but you can use long if you are worried about it. If that still gives you weird results, then the problem is with your algorithm.
Use BigInt.
Then again, unsigned int stores values up to over 4 billion, so you shouldn't be having any problems even with "sum of all fibonacci numbers up to 4 million" (which, obviously, has to be less than 8 mil)?
Your program prints F_1 + ..+ F_limit and not F_1 + ... F_n with F_n < limit as you described.
Check the Wikipedia article on Fibonacci Numbers and Sloane A000045: Fibonacci numbers grows exponentially. Checking this table F_48 = 4807526976 which exceeds int. F_100 is 354224848179261915075 which surely overflows even int64_t (your stack doesn't, though).
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.
int main()
{
long first = 1, second = 2, next, c;
int sum=0;
for ( c = 1 ; c <100000000; c++ )
{
next = first + second;
if(next>=4000000)
{
next= next-second;
break;
}
first = second;
second = next;
if(next%2==0){
sum=sum+next;
}
}
printf("the sum of even valued term is %d\n",sum+2);
}
Here's my program:
#include <iostream>
long int even_sum_fibonacci(int n){
int i = 8;
int previous_i = 2;
int next_i = 0;
long int sum = previous_i + i;;
while(n>next_i){
next_i = i*4 + previous_i;
previous_i = i;
i = next_i;
sum = sum + i;
}
return sum - next_i; //now next_i and i are both the bigger number which
//exceeds 4 million, but we counted next_i into sum
//so we'll need to substract it from sum
}
int main()
{
std::cout << even_sum_fibonacci(4000000) << std::endl;
return 0;
}
Because if you look at the fibonacci series (at the first few even numbers)
2 8 34 144 610 2584 ... you'll see that it matches the pattern that
next_number = current_number * 4 + previous_number.
This is one of solutions. So the result is 4613732
You can try the below code.
public static void SumOfEvenFibonacciNumbers()
{
int range = 4000000;
long sum = 0;
long current = 1;
long prev = 0;
long evenValueSum= 0;
while (evenValueSum< range)
{
sum = prev + current;
prev = current;
current = sum;
if (sum % 2 == 0 )
{
evenValueSum = evenValueSum+ sum;
}
}
Console.WriteLine(evenValueSum);
}
You can use the above code.
import numpy as np
M = [[0,1],[1,1]]
F = [[0],[1]]
s = 0
while(F[1][0] < 4000000):
F = np.matmul(M, F)
if not F[0][0]%2:
s+=F[0][0]
print(s)
We can do better than this in O(log n) time. Moreover, a 2 × 2 matrix and a two dimensional vector can be multiplied again in O(1) time. Therefore it suffices to compute Mn.
The following recursive algorithm computes Mn
If n = 0, return I2
If n = 1, return M.
If n = 2m.
Recursively compute N = Mm, and set P = N2.
If n = 2m+1, set P = PM.
Return P.
We have T(n) = T(n/2) + O(1), and by master's theorem T(n) = O(log n)
You can also use recurrence for Even Fibonacci sequence is:
EFn = 4EFn-1 + EFn-2
with seed values
EF0 = 0 and EF1 = 2.
SIMPLE SOLUTION WOULD BE:-
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n1=1;
int n2=2;
int num=0,sum;
for (int i=1;i,n1<4000000;i++)
{
cout<<" "<<n1;
num=n1+n2;
if(!(n1%2))
{
sum+=n1;
}
n1=n2;
n2=num;
}
cout<<"\n Sum of even term is = "<<sum;
return 0;
}
Here's my offer, written in Java. I had been using a for loop whose exit value was 4000000 but realized early on there was a serious overflow for the sum of the numbers. Realizing the Fibonacci Number has to be less than 4 million (and not the sum), I changed to a while loop and got it:
class Main {
public static void main(String[] args) {
int counter = 0;
int fibonacciSum = 0, fibonacciNum = 0;
int previous = 1, secondPrevious = 0;
fibonacciNum = previous + secondPrevious;
while (fibonacciNum <= 4000000){
if (fibonacciNum % 2 == 0 ){
counter++;
fibonacciSum += fibonacciNum;
secondPrevious = previous;
previous = fibonacciNum;
}//ends if statement
else {
secondPrevious = previous;
previous = fibonacciNum;
}//ends else statement
fibonacciNum = previous + secondPrevious;//updates number
}//ends loop
System.out.println("\n\n\n" + fibonacciSum);
}//ends main method
}//ends Main