Need two C program that will: 1. The decimal number, 585 = 1001001001 (binary),
ID: 3543599 • Letter: N
Question
Need two C program that will:
1. The decimal number, 585 = 1001001001 (binary), is palindromic in base-10 and base-2. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. Do not consider leading zeros while checking for palindromes!
2. Each new term in the Fibonacci sequence is the sum of the previous two terms. Starting with 1 and 2, the first 10 terms are: 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 (a) the even-valued terms; and (b) the odd-valued terms.
Explanation / Answer
// PROGRAM 1.
#include<stdio.h>
int is_palin_in_both(int k)
{
int local = k;
int real = k;
int reverse = 0;
while(k > 0)
{
reverse = reverse * 10 + (k%10);
k = k / 10;
}
if(local!=reverse)
{
return 0;
}
// if we came here means we already integer palindrome...
reverse = 0;
while(local!=0)
{
reverse <<= 1;
reverse |= (local & 1);
local >>= 1;
}
if(reverse!=real) return 0;
//// if we came here means we already Binary palindrome...
return 1;
}
int main()
{
int i=0;
int sum =0;
while(i<100000)
{
if(is_palin_in_both(i))
sum = sum + i;
i++;
}
printf("Sum of palindromes in both binary and integer in less than million is %d",sum);
return 0;
}
// PROGRAM 2
#include<stdio.h>
int main()
{
int end_value = 4000000;
int a = 1;
int b = 2;
int c=0;
int even_fib_sum = 0;
int odd_fib_sum = 0;
while(c<4000000)
{
c = a +b;
//printf("%d ",c);
if(c%2==0) even_fib_sum = even_fib_sum+c;
if(c%2!=0) odd_fib_sum = odd_fib_sum+c;
a = b;
b = c;
}
printf(" Sum of even-valued terms is %d",even_fib_sum);
printf(" Sum of odd-valued terms is %d",odd_fib_sum);
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.