C - Find all amicable numbers between limits - c

First a definition: An amicable pair of numbers consists of two different integers where the
sum of the divisors of the first integer is equal to the second integer, and the
sum of the divisors of the second integer is equal to the first integer. A perfect number is a number that equals the sum of its own divisors.
What I want to do is make a program that asks the user for a lower limit, and an upper limit and then presents him/her with all the amicable pairs (one per line) between those two limits. If there's a perfect number only one number needs to be printed (not a pair in its case).
The whole idea is pretty confusing to me, so I'm looking for some assistance.
Here's what I have to start with, I know that sumDivisors() should be more or less correct, but main() is merely checking if the two inputted numbers are amicable or not - might have to do a complete overhaul of this since I want all the pairs between two given limits.
long sumDivisors(long a)
{
long s=0,i;
for(i=1;i<=a/2;i++)
{
if(a%i==0)
{
s+=i;
}
}
return s;
}
int main()
{
long t,n,s1;
scanf("%ld",&t);
while(t--)
{
scanf("%ld",&n);
s1=sumDivisors(n);
if(n==sumDivisors(s1))
{
printf("Yes\n");
}
else printf("No\n");
}
return 0;
}

You could write main() like this:
int main ()
{
// assumes 1 <= min <= max
long min = 1;
long max = 10000;
for (long a = min; a <= max; a++) {
long b = sum_of_proper_divisors (a);
if (a == b) {
printf ("perfect number:\t%ld\n", a);
}
if ((a < b) && (b <= max) && (sum_of_proper_divisors (b) == a)) {
printf ("amicable pair:\t(%ld, %ld)\n", a, b);
}
}
return 0;
}

The most easiest and understandable way of finding amicable pairs between a range is as follows:
find amicable pairs between 1 to 2000.if you want between 1 to 3000 , just bring changes in the checking condition of for loops( i and j <= 3000).
You can give whatever range you want (by changing the initialization and checking conditions of the loops(outer loop and inner loop) .
#include<stdio.h>
int main(){
int i,j;
//outer loop.
for (i=1;i<=2000;i++){
int d1=1;
int sum1=0;
while(d1<i){
if(i%d1==0){
sum1+=d1; //sum of divisors of i
d1++;
}else
d1++;
}
//inner loop
for(j=i+1;j<=2000;j++){
int d2=1;
int sum2=0;
while(d2<j){
if(j%d2==0){
sum2+=d2;//sum of divisors of j
d2++;
}else
d2++;
}
if(sum1==j && sum2==i)
//printing amicalbe pair.
printf("(%d , %d) \n",i,j);
}
}
return 0;
}

Most of you might face problem understanding what amicable pairs are, let me explain it through an example 220 & 284 are said to be amicable pairs because if we find the proper divisors of 220 we get (1, 2, 4, 5, 10, 11, 20, 22, 44, 55 & 110) summing up all of them we get 284. Now, the proper divisors of 284 are (1, 2, 4, 71 & 142) summing up all of them we get 220. Similarly, the sum of the divisors of 1184 is equal 1210 & the sum of the divisors of 1210 is equal to 1184. Now, we write a program in C to find all the amicable pairs within the range of 10000.
int main()
{
int n,k;
int i=1,s1=0,s2=0;
for(k=1;k<=10000;k++)
{
n=k;
while(i<n)
{
if(n%i==0)
s1=s1+i;
i++;
}
i=1;
if(s1==n)
continue;
while(i<s1)
{
if(s1%i==0)
s2=s2+i;
i++;
}
if(n==s2)
printf("%d \n",n);
s1=0;
s2=0;
}
}

Related

Need to make code efficient and reduce time complexity

Given a range [ L , R ] (both inclusive), I have to tell find the maximum difference between two prime numbers in the given range. There are three answers possible for the given range.
If there is only one distinct prime number in the given range, then maximum difference in this case would be 0.
If there are no prime numbers in the given range, then output for this case would be -1.
Example:
Range: [ 1, 10 ]
The maximum difference between the prime numbers in the given range is 5.
Difference = 7 - 2 = 5
Range: [ 5, 5 ]
There is only one distinct prime number so the maximum difference would be 0.
Range: [ 8 , 10 ]
There is no prime number in the given range so the output for the given range would be -1.
Input Format
The first line of input consists of the number of test cases, T
Next T lines each consists of two space-separated integers, L and R
Constraints
1<= T <=10
2<= L<= R<=10^6
This is my code:
#include <stdio.h>
int isprime(int n)
{
int i,c=0;
for(i=1;i<n;i++)
{
if(n%i==0)
c++;
}
if(c==1)
return 1;
else
return 0;
}
int main()
{
int t; //testnumber
scanf("%d",&t);
for(int k=0;k<t;k++)
{
int l,r; //l=low or floor, r = highest range or ceiling;[l,r]
scanf("%d%d",&l,&r);
int n = r-l; //difference in range
int a[n];
int j=0;
for(int i=l;i<=r;i++)
{
if(isprime(i)==1)
{
a[j] = i;
j++;
}
}
int d = a[j-1]-a[0];
if(j==0)
printf("%d\n",-1);
else
printf("%d\n",d);
}
return 0;
}
When posting on a forum/stack or asking for review, try to name your variables appropriately. Otherwise, it becomes uneasy to follow the code or what is the purpose of which variable.
I wrote the code below hoping you will understand my implementation.
#include <iostream>
#include <math.h>
using namespace std;
void isPrime(int num, int* primeNumber)
{
if (num == 2)
{
*primeNumber = num; //2 is a prime number
return;
}
if (num%2 == 0)
{
return; //num is an even number, so, not prime
}
int limit = sqrt(num);
if (limit*limit == num)
{
return; //num is a square number, so, not prime
}
for (int i = 3; i <= limit; i=i+2)//to find if a number is prime or not, we only have to divide it from 2 to sqrt(num).
{ //i=i+2 skips even number, cause already checked if num is even or not.
if (num % i == 0)
{
return; //`num` is divisible by i, so, not prime
}
}
*primeNumber = num; //no divisible number found. so, num is prime.
}
int main()
{
int testNumber;
cout<< "Enter testNumber: ";
cin>> testNumber;
for (int i = 0; i < testNumber; ++i)
{
int newLow, low, high, lowestPrime = 0, highestPrime = -1;
cin>> low>> high;
newLow = low;
if (low == high)
{
cout<<"0\n";
continue;
}
for (int j = low; j <= high; ++j)//find the lowest prime
{
isPrime(j, &lowestPrime);
if (lowestPrime != 0)//if lowest prime found, lowestprime will no longer be 0
{
//cout<<"lowest prime: "<<lowestPrime<<endl;
newLow = j; //there is no prime number between low...newLow
break;
}
}
for (int j = high; j >= newLow; j--)//find highest prime
{
isPrime(j, &highestPrime);
if (highestPrime != -1)//if highest prime found, highestprime will no longer be -1
{
//cout<<"highest prime: "<<highestPrime<<endl;
break;
}
}
cout<<highestPrime - lowestPrime<<"\n";
}
return 0;
}
This task doesn't require any special algorithm(except checking if number is prime in O(sqrt(N))) to be solved efficiently. Think about prime numbers, what is the frequency of them on some range (for example on range from 1 to 100) what is some "pattern" that appears. Now, if i understood the task correctly you need to find maximal difference of primes on range which is last_prime_on_range - first_prime_on_range, from this and previous observation you can easily devise an efficient algorithm.
Spoiler:
You don't need to check whole range, it would be enough to check from L to L+100
and from R to R-100, obviously if L+100>R you can just go from L to R.
If you want to be sure you can go from L to L+1000 and from R to R-1000 since it doesn't impact time complexity too much.
Also, adding a break; when you find a prime would also solve the problem.
Note that this gap between primes is not guaranteed to be bellow 100/1000 but for given range checking up to 1000 would be enough.
Now if you need to check all primes in range, you should learn about Sieve Of Eratosthenes.

How to see if numbers have same digits in array?

I'm a bit stuck on one of my problems not because I don't know, but because I can't use more complex operations.(functions and multiple arrays)
So I need to make a program in C that ask for an input of an array(max 100 elements) and then program needs to sort that matrix by numbers with same digits.
So I made everything that I know, I tested my program with sorting algorithm from minimum to maximum values and it works, only thing that I can't understand is how should I test if the number have same digits inside the loop? (I can't use functions.)
So I know the method of finding if the number have the same digits but I don't know how to compare them. Here is an example of what I need.
This is what I have for now this sorts numbers from min to max.
#include <stdio.h>
int main() {
int matrix[100];
int i,j;
int temp,min;
int elements_number=0;
printf("Enter the values of matrix-max 100 elements-type -1 to end: ");
for(i=0;i<100;i++){
scanf("%d",&matrix[i]);
elements_number++;
if(matrix[i]==-1){
elements_number--;
break;
}
}
for (i=0; i<elements_number; i++) {
min=i;
for (j=i+1; j<elements_number; j++) {
if (matrix[j] < matrix[min])
min = j;
}
temp = matrix[i];
matrix[i] = matrix[min];
matrix[min] = temp;
}
for(i=0;i<elements_number;i++){
if(i!=elements_number-1){
printf("%d,",matrix[i]); }
else printf("%d.",matrix[i]);
}
return 0;
}
I need this output for these numbers:
INPUT :
1 22 43 444 51 16 7 8888 90 11 -1
OUTPUT:
1,22,444,7,8888,11,43,51,16,90.
Integers with 1 digit count as "numbers with same number of digits" like 7 and 1 in this example.
Hope that you can help.
After processing the array, the single-digit numbers should all be in the left part of the array, the other numbers in the right part. Within each part, the original order of the elements should be preserved. This is called a stable partition. It is different from sorting, because the elements are only classified into two groups. Sorting means that there is a clear relationship between any two elements in the array.
This can be done by "filtering" the array for single-digit numbers and storing the other numbers that were filtered out in a temporary second array. Then append the contents of that second array to the (now shorter) first array.
Here's how that could work:
#include <stdlib.h>
#include <stdio.h>
void print(const int *arr, int n)
{
for (int i = 0; i < 10; i++) {
if (i) printf(", ");
printf("%d", arr[i]);
}
puts(".");
}
int is_rep_digit(int n)
{
int q = n % 10;
n /= 10;
while (n) {
if (n % 10 != q) return 0;
n /= 10;
}
return 1;
}
int main()
{
int arr[10] = {1, 22, 43, 444, 51, 16, 7, 8888, 90, 11};
int aux[10]; // auxliary array for numbers with several digits
int i, j, k;
print(arr, 10);
j = 0; // number of single-digit numbers
k = 0; // number of other numbers
for (i = 0; i < 10; i++) {
if (is_rep_digit(arr[i])) {
arr[j++] = arr[i]; // pick single-digit number
} else {
aux[k++] = arr[i]; // copy other numbers to aux
}
}
k = 0;
while (j < 10) { // copy aux to end of array
arr[j++] = aux[k++];
}
print(arr, 10);
return 0;
}
Edit: I've just seen your requirement that you can't use functions. You could use Barmar's suggestion to test divisibility by 1, 11, 111 and so on. The tricky part is to find the correct divisor, however.
Anyway, the point I wanted to make here is that you don't need a full sorting algorithm here.

Finding numbers with unique digits in C

I have to write a program that finds every number (except 0) which can be factored by numbers from 2-9.
For example first such a number would be number 2520 as it can be divided by every single number from 2 to 9.
It also has to be a number that contains only 1 type of digit of its own (no multiple digits in a number). So for example 2520 will not meet this requirement since there are two same digits (2). The example of a number that meets both requirements is number 7560. That is the point I don't how to do it. I was thinking about converting value in an array to string, and then putting this string in another array so every digit would be represented by one array entry.
#include <stdio.h>
#include <math.h>
int main() {
int i, n, x, flag, y = 0;
scanf("%d", &n);
double z = pow(10, n) - 1;
int array[(int)z];
for (i = 0; i <= z; i++) {
flag = 0;
array[i] = i;
if (i > 0) {
for (x = 2; x <= 9; x++) {
if (array[i] % x != 0) {
flag = 1;
}
}
if (flag == 0) {
y = 1;
printf("%d\n", array[i]);
}
}
}
if (y == 0) {
printf("not exist");
}
return 0;
}
This should give you a base:
#include <stdio.h>
#include <string.h>
int main()
{
char snumber[20];
int number = 11235;
printf("Number = %d\n\n", number);
sprintf(snumber, "%d", number);
int histogram[10] = { 0 };
int len = strlen(snumber);
for (int i = 0; i < len; i++)
{
histogram[snumber[i] - '0']++;
}
for (int i = 0; i < 10; i++)
{
if (histogram[i] != 0)
printf("%d occurs %d times\n", i, histogram[i]);
}
}
Output:
Number = 11235
1 occurs 2 times
2 occurs 1 times
3 occurs 1 times
5 occurs 1 times
That code is a mess. Let's bin it.
Theorem: Any number that divides all numbers in the range 2 to 9 is a
multiple of 2520.
Therefore your algorithm takes the form
for (long i = 2520; i <= 9876543210 /*Beyond this there must be a duplicate*/; i += 2520){
// ToDo - reject if `i` contains one or more of the same digit.
}
For the ToDo part, see How to write a code to detect duplicate digits of any given number in C++?. Granted, it's C++, but the accepted answer ports verbatim.
If i understand correctly, your problem is that you need to identify whether a number is consisted of multiple digits.
Following your proposed approach, to convert the number into a string and use an array to represent digits, i can suggest the following solution for a function that implements it. The main function is used to test the has_repeated_digits function. It just shows a way to do it.
You can alter it and use it in your code.
#include <stdio.h>
#define MAX_DIGITS_IN_NUM 20
//returns 1 when there are repeated digits, 0 otherwise
int has_repeated_digits(int num){
// in array, array[0] represents how many times the '0' is found
// array[1], how many times '1' is found etc...
int array[10] = {0,0,0,0,0,0,0,0,0,0};
char num_string[MAX_DIGITS_IN_NUM];
//converts the number to string and stores it in num_string
sprintf(num_string, "%d", num);
int i = 0;
while (num_string[i] != '\0'){
//if a digit is found more than one time, return 1.
if (++array[num_string[i] - '0'] >= 2){
return 1; //found repeated digit
}
i++;
}
return 0; //no repeated digits found
}
// test tha function
int main()
{
int x=0;
while (scanf("%d", &x) != EOF){
if (has_repeated_digits(x))
printf("repeated digits found!\n");
else
printf("no repeated digits\n");
}
return 0;
}
You can simplify your problem from these remarks:
the least common multiple of 2, 3, 4, 5, 6, 7, 8 and 9 is 2520.
numbers larger than 9876543210 must have at least twice the same digit in their base 10 representation.
checking for duplicate digits can be done by counting the remainders of successive divisions by 10.
A simple approach is therefore to enumerate multiples of 2520 up to 9876543210 and select the numbers that have no duplicate digits.
Type unsigned long long is guaranteed to be large enough to represent all values to enumerate, but neither int nor long are.
Here is the code:
#include <stdio.h>
int main(void) {
unsigned long long i, n;
for (n = 2520; n <= 9876543210; n += 2520) {
int digits[10] = { 0 };
for (i = n; i != 0; i /= 10) {
if (digits[i % 10]++)
break;
}
if (i == 0)
printf("%llu\n", n);
}
return 0;
}
This program produces 13818 numbers in 0.076 seconds. The first one is 7560 and the last one is 9876351240.
The number 0 technically does match your constraints: it is evenly divisible by all non zero integers and it has no duplicate digits. But you excluded it explicitly.

C program which is finding "happy" nums recursively

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.)

final step: adding all the primes that the reverse are also primes

like 17, is a prime, when reversed, 71 is also a prime.
We manage to arrive at this code but we cant finish it.
#include <stdio.h>
main()
{
int i = 10, j, c, sum, b, x, d, e, z, f, g;
printf("\nPrime numbers from 10 to 99 are the follwing:\n");
while (i <= 99)
{
c=0;
for (j = 1; j <= i; j++)
{
if (i % j == 0) c++;
}
if (c == 2)
{
b = i;
d = b / 10;
e = b - (10 * d);
x = (e * 10) + d;
{
z = 0;
f = x;
for (j = 1; j <= f; j++)
{
if (f % j == 0) z++;
}
if (z == 2)
{
printf("%d %d\n", i, f);
}
}
}
i++;
}
getch();
}
my problem is how to add all the fs..
the answer should be 429.
how can i add all the f?
Why don't you break up the code into some functions:
bool isPrime(int number) that checks if a number is prime.
int reverse(int number) that reverses the number.
Then the algorithm would be:
sum = 0;
for (i = 2; i <= 99; ++i)
if (isPrime(i) && isPrime(reverse(i)))
sum += i;
At the beginning initialize sum = 0;. Then, next to your printf count the prime: sum += i;. you can then print it at the end.
If this is a basic programming class and you are just interested in the result then this will get you there, however if it is an algorithms class then you may want to look at the Sieve of Eratosthenes.
You may also want to think about what makes a 2 digit number the reverse of another 2 digit number and how you would express that.
There are many problems in your code. None of them will prevent compilation and none of them will cause problems in getting the output. I'll first tell you how to get the result you want and then highlight the problems.
Here is your code, modified to sum fs. You just need to add f to sum every time you print a prime satisfying the condition. Finally, you should print the sum of all fs.
#include <stdio.h>
//Use int as the return type explicitly!
int main()
{
int i=10,j,c,sum,b,x,d,e,z,f,g;
printf("\nPrime numbers from 10 to 99 are the follwing:\n");
//Set the sum of all primes whose reverse are also primes to zero
sum = 0;
while(i<=99)
{
//c is tyhe number of factors.
c=0;
for(j=1;j<=i;j++)
{
if(i%j==0)
c++;
}
//If there are only two factors.
//Two factors (1 and itself) => Prime
if(c==2)
{
//Reverse i and store it in x
b=i;
d=b/10;
e=b-(10*d);
x=(e*10)+d;
//Curly braces unnecessary
{
//Check if the reverse i.e. x is prime
//z is the number of factors
z=0;
//f is the number being tested for primality.
f=x;
for(j=1;j<=f;j++)
{
if(f%j==0)
z++;
}
//If f i.e. x i.e. the reverse has only two factors
//Two factors (1 and itself) => Prime
if(z==2)
{
//print the prime number.
printf("%d %d \n",i,f);
//Add f to the sum
sum += f;
}//if(z==2)
}//Unnecessary braces
}//if(c==2)
i++;
}//end while
//print the number of reversed primes!!
//That is sum of the reversed values of numbers satisfying the
//condition!
printf("\nThe sum is:%d\n", sum);
//getch() is non standard and needs conio.h
//Use getchar() instead.
//Better solution needed!!
getchar();
//Return 0 - Success
return 0;
}
Output
...#...-desktop:~$ gcc -o temp temp.c
...#...-desktop:~$ ./temp
Prime numbers from 10 to 99 are the follwing:
11 11
13 31
17 71
31 13
37 73
71 17
73 37
79 97
97 79
The sum is:429
...#...desktop:~$
Do take note of all the comments made in the code (above). In addition, consider doing the following:
Removing the unnecessary braces.
Using one variable for one thing. (x could have been used instead of f).
Using better variable names like number and numberOfFactors.
Breaking up your code into functions as Mehrdad Afshari has suggested.
Consider testing primality by checking if there is a divisor of the number (num) being tested up to sqrt(num) (Square root of the number).
Consider this:
For numbers upto 99, the reversed numbers are also 2 digit numbers.
If the number is in the set of primes already found, you can verify easily.
This will reduce the number of checks for primality. (which are expensive)
To do the above, maintain a list of primes that have been identified (primeList)
as well as a list of reversed primes (revList). Any item in revList that is also
in primeList satisfies your condition. You can then easily obtain the sum (429)
that you need.
Look at sweet61's answer, the use of the Sieve of Eratosthenes with my method will definitely be much more efficient. You can reverse primes at the end of the sieve and populate the revList (at the end).
On a personal level, I try to find the best solution. I hope you will also attempt to do the same. I have tried to help you out without giving it all away.
I hope this helps.
Note
I had suggested checking for divisors up to num/2. I fixed it to sqrt(num) on vartec's suggestion.

Resources