Wednesday, November 30, 2016

Twin Primes

Lia is fascinated by anything she considers to be a twin. She calls a pairs of positive integers,  and , twins if:
• They are both prime. A prime number is an integer greater than  that has no positive divisors other than  and itself.
• Their absolute difference is exactly equal to  (i.e., ).
Given an inclusive interval of integers from  to , can you help Lia find the number of pairs of twins there are in the interval (i.e., )? Note that pairs  and  are considered to be the same pair.
Input Format
Two space-separated integers describing the respective values of  and .
Constraints
Output Format
Print a single integer denoting the number of pairs of twins.
Sample Input 0
3 13

Sample Output 0
3

Explanation 0
There are three pairs of twins: , and .

********************
PROGRAM
********************

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int checkPrime(long long int n)
{
long long int i;
for(i=2;i<n;i++)
if(n%i==0)
return 0;
return 1;
}

int main() {

/* Enter your code here. Read input from STDIN. Print output to STDOUT */
long long int m,n,i;
scanf("%lld%lld",&n,&m);
long long int c=0;
if((m-n)<=1000000 && n>=1 && m>=n && n<=1000000000 && m<=1000000000)
{
if(n>2)
{
if(n%2==0)
n++;
for(i=n;i<=m;i=i+2)
{
if(checkPrime(i)==1)
{
if(checkPrime(i+2)==1)
{
c++;
}
}
}
}

else
{
n=3;
for(i=n;i<=m;i=i+2)
{
if(checkPrime(i)==1)
{
if(checkPrime(i+2)==1)
{
c++;
}
}
}
}
printf("%lld",c);
}
else
printf("0");
return 0;
}

Tuesday, November 29, 2016

Best Divisor

Kristen loves playing with and comparing numbers. She thinks that if she takes two different positive numbers, the one whose digits sum to a larger number is better than the other. If the sum of digits is equal for both numbers, then she thinks the smaller number is better. For example, Kristen thinks that  is better than  and that  is better than .
Given an integer, , can you find the divisor of  that Kristin will consider to be the best?
Input Format
A single integer denoting .
Constraints
Output Format
Print an integer denoting the best divisor of .
Sample Input 0
12

Sample Output 0
6

Explanation 0
The set of divisors of  can be expressed as . The divisor whose digits sum to the largest number is  (which, having only one digit, sums to itself). Thus, we print  as our answer.
************************
PROGRAM
************************

#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int sumofdigits(int n)
{
int sum=0;
while(n>0)
{
sum=sum+(n%10);
n=n/10;
}
return sum;
}
int main(){
int n,sum=0,ans;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
int temp=sumofdigits(i);
if(temp>sum)
{
sum=temp;
ans=i;
}

}
}
printf("%d",ans);
return 0;
}