Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers.
For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; therefore d(220) = 284. The proper divisors of 284 are 1, 2, 4, 71 and 142; so d(284) = 220.
Evaluate the sum of all the amicable numbers under 10000.
题目大意:
d(n)定义为n 的所有真因子(小于 n 且能整除 n 的整数)之和。 如果 d(a) = b 并且 d(b) = a, 且 a b, 那么 a 和 b 就是一对相亲数(amicable pair),并且 a 和 b 都叫做亲和数(amicable number)。
例如220的真因子是 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 和 110; 因此 d(220) = 284. 284的真因子是1, 2, 4, 71 和142; 所以d(284) = 220.
计算10000以下所有亲和数之和。
#include<stdio.h> int FactorSum(int n) //计算n的所有小于n的因素和 { int i; int sum=1; for(i=2; i<=n/2; i++) { if(n%i==0) sum+=i; } return sum; } int main() { int t,i=2; int sum=0; while(i<10000) { t=FactorSum(i); if(t!=i && FactorSum(t)==i) sum+=i; i++; } printf("%d ",sum); return 0; }
Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 53 = 49714.
What is the total of all the name scores in the file?
题目大意:
文件names.txt (右键另存为)是一个46K大小的文本文件,包含5000多个英文名字。利用这个文件,首先将文件中的名字按照字母排序,然后计算每个名字的字母值,最后将字母值与这个名字在名字列表中的位置相乘,得到这个名字的得分。
例如将名字列表按照字母排序后, COLIN这个名字是列表中的第938个,它的字母值是3 + 15 + 12 + 9 + 14 = 53。所以COLIN这个名字的得分就是938 53 = 49714.
文件中所有名字的得分总和是多少?
#include <stdio.h> #include <ctype.h> #include <stdlib.h> struct str{ char name[12]; }; char a[12]; int namevalue(char *s) { int i, sum; i = sum = 0; while(s[i]) { sum += (s[i] - 'A' + 1); i++; } return sum; } int cmp(const void *a, const void *b) { return strcmp((*(struct str*)a).name, (*(struct str*)b).name); } void solve(void) { FILE *fp; int i, j, k; char *s, c; long long sum = 0; struct str namestring[5163]; fp = fopen("names.txt", "r"); fseek(fp, 0, SEEK_END); int file_size; file_size = ftell(fp); fseek(fp, 0, SEEK_SET); s = (char*)malloc(file_size * sizeof(char)); fread(s, sizeof(char), file_size, fp); i = j = k = 0; while(i <= file_size) { c = s[i++]; if(!isalpha(c)) { if(c == ',') { j = 0; strcpy(namestring[k++].name, a); memset(a,'