The beauty of algorithms [from cainiao to expert drills]: some small algorithms

Source: Internet
Author: User
1. Number of completions within 10000
/** Problem description: calculate the number of completions within 10000. * End number: the sum of a number equal to its different factors * For example, 6 = 1 + 2 + 3.8! = 1 + 2 + 4 * xtfggef 2012/5/16 */# include <iostream> # include <fstream> # include <vector> using namespace STD;/** train of thought: calculate the number less than 10000, put it in * a vector, and compare it with the given number. If it is less than *, print it. Another idea is to directly calculate the number less than the given number, so that you can calculate less. */INT main (INT argc, char * argv []) {// introduce the file operation ifstream CIN ("seed.txt"); int N; vector <int>; /** here we need to explain why the for * loop below is I = I + 2, which indicates that the complete number is only in the even number, the odd number does not have a complete number in a small range. * The specific range does not exist in the mathematics field. */For (INT I = 2; I <10000; I = I + 2) {int sum = 1; for (Int J = 2; j <= I/2; j ++) {// if the Division is 0, it is a factor, so add if (I % J = 0) sum = sum + J;} If (sum = I). push_back (I) ;}while (CIN >>n) {cout <n <":"; for (int K = 0; k <. size (); k ++) {if (a [k] <= N) cout <"" <A [k] ;}cout <Endl ;} return 0 ;}

Baidu Encyclopedia of the number of: http://baike.baidu.com/view/640632.htm

2. Calculate the three-digit symmetric Prime Number

/** Problem description: Find a three-digit symmetric Prime Number * For example, 101 is, 787 is also, 896 is not * is input yes, otherwise, no * xtfggef 2012/5/16 */# include <iostream> # include <cmath> using namespace STD; bool isprime (INT); int main (INT argc, char * argv []) is output. {int N; CIN> N; // core cout <(n> 100 & n <1000 & N/100 = n % 10 & isprime (n )? "Yes \ n": "No \ n"); Return 0;}/** determine whether it is a prime number */bool isprime (int n) {int sqr = SQRT (N * 1.0); For (INT I = 2; I <= sqr; I ++) {If (N % I = 0) return false;} return true ;}

3. Calculate the maximum common divisor of two numbers.

/** Calculate the maximum common divisor of two numbers * xtfggef 2012/5/16 */# include <stdio. h> int gcd (INT, INT); void main () {int A = 5; int B = 8; int c = gcd (A, B ); printf ("% d \ n", c);} int gcd (int A, int B) {While (! = B) {If (A> B) A = A-B; elseb = B-A;} return ;}

The minimum public multiples are similar. With the help of the minimum public multiples = x * Y/gcd (x, y); then OK.

Note: to make the calculation not out of the range, it is best to write it as: X/gcd (x, y) * y

4. Replace the modulo operation method

K = (J + rotdist) % N
It can be written as follows:
K = J + rotdist;
If (k> N)
K-= N;

5. Calculate the largest sum of adjacent subvectors (from the programming pearl)

/** Find out the largest of any adjacent sub-vectors and * xtfggef 2012/5/7 */# include <stdio. h> int max (int A, int B) {return (A> B )? A: B;} void main () {int A [10] = {31,-, 26,-, 58, 97,-93 }; int maxsofar = 0; int maxendinghere = 0; For (INT I = 0; I <10; I ++) {// in case of a negative number, assign 0 directly, this is equivalent to skipping // a large number. maxendinghere = max (maxendinghere + A [I], 0); maxsofar = max (maxsofar, maxendinghere );} printf ("% d \ n", maxsofar );}

6. If an integer array a is given and the number of elements is N, find the element that appears n/2 or more times in a and print it out.

Package COM. xtfggef. hashmap; import Java. util. hashmap; import Java. util. map; import Java. util. set; /*** print the n/2 or more elements in the array * use a hashmap to store array elements and the number of occurrences * @ author erqing **/public class hashmaptest {public static void main (string [] ARGs) {int [] A = {,}; Map <integer, integer> map = new hashmap <integer, integer> (); For (INT I = 0; I <. length; I ++) {If (map. containskey (A [I]) {int TMP = map. get (A [I]); TMP + = 1; map. put (A [I], TMP);} else {map. put (A [I], 1) ;}} set <integer> set = map. keyset (); For (integer S: Set) {If (map. get (s)> =. length/2) {system. out. println (s );}}}}

7. Java implementation of hdoj problem 1000

import java.util.Scanner;public class Main {    public static void main(String[] args) {        Scanner in = new Scanner(System.in);        while(in.hasNextInt()){                int a = in.nextInt();            int b = in.nextInt();            int c = sum(a,b);            System.out.println(c);        }    }    public static int sum(int a,int b){        return a+b;    }}

8. hdoj problem 1001 C ++ implementation

#include <iostream>using namespace std;int main(){    unsigned int num;     while (cin >> num)    {        cout << (1+num)*num/2 << endl << endl ;     }    return 0;}

9. Java implementation of hdoj problem 1002

import java.math.BigInteger;import java.util.Scanner;public class Main{    public static void main(String[] args)     {        Scanner scanf = new Scanner(System.in);        while(scanf.hasNext())        {            int n;            int i=1,x=0;            n=scanf.nextInt();            while(n--!=0)           {               if(x++!=0)                   System.out.println();               BigInteger a,b,sum;               a=scanf.nextBigInteger();               b=scanf.nextBigInteger();               sum=a.add(b);               System.out.println("Case"+" "+ i++ +":");               System.out.print(a+" "+"+"+" "+b+" "+"="+" ");               System.out.println(sum);           }        }    }}

10. transpose the JAVA Implementation Matrix

Package COM. xtfggef. algo;/*** transpose of the matrix ** @ author erqing **/public class Matrix {public static void main (string [] ARGs) {int array [] [] = {1, 2, 3}, {4, 5, 6}, {7, 8, 9 }}; int array2 [] [] = new int [3] [3]; system. out. println ("transpose front:"); For (INT I = 0; I <array. length; I ++) {for (Int J = 0; j <array [I]. length; j ++) {system. out. print (array [I] [J] + ""); array2 [J] [I] = array [I] [J];} system. out. println ();} system. out. println ("transposed:"); For (int K = 0; k <array2.length; k ++) {for (INT h = 0; H <array2 [K]. length; H ++) {system. out. print (array2 [k] [H] + "");} system. out. println ();}}}

11. Time Difference in Java computing

import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class Tiemp {    public static void main(String args[]){        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");        String s1 = "20080808";        String s2 = "20080908";        try {            Date d1 = sdf.parse(s1);            Date d2 = sdf.parse(s2);            System.out.println((d2.getTime() -  d1.getTime())/(3600L*1000));         } catch (ParseException e) {            e.printStackTrace();        }    }}

12. Determine IP Legality

1. From the number of. values, there cannot be more than three

2. The number between each vertex must be 0 ~ Between 255

3. Each number except. Must be <9 and> 0

4. The first and last characters cannot be.

# Include <stdio. h> int is_valid_ip (const char * IP) {int section = 0; // The decimal value of each section is int dot = 0; // Several separators int last =-1; // The if (* IP! = '. ') {While (* IP) {If (* IP = '. ') {dot ++; If (DOT> 3) {return 0;} If (section >=0 & section <= 255) {Section = 0 ;} else {return 0 ;}} else if (* IP >='0' & * IP <= '9 ') {Section = Section * 10 + * IP-'0'; If (last = '0') {return 0 ;}} else {return 0 ;}last = * IP; IP ++;} If (section >=0 & section <= 255) {If (3 = dot) {Section = 0; printf ("ip address success! \ N "); Return 0 ;}} return 1 ;}else {printf (" format error! "); Return 0 ;}} int main () {is_valid_ip (" 23.249.22.123 "); Return 0 ;}

13. judge whether the string is a return message.

# Include <stdio. h> # include <stdlib. h>/* determine whether the user-input string is a return object * a return object refers to a string with the same reading and reverse reading. * For example, abccba is a return object, abcdab is not a echo */INT palindrome (const char * Str) {int length = strlen (STR); For (INT I = 0; I <= length/2; I ++) {If (STR [I]! = STR [length-i-1]) {return-1 ;}} return 1 ;}int main () {char s [100]; gets (s ); int result = palindrome (s); If (result = 1) {printf ("the string is a 文"");} else {printf ("the string is not a 文 ");}}

14. convert a string to an integer

#include<iostream>#include<string>#include<assert.h>using namespace std;int str_2_int(string str){assert(str.size()>0);int pos = 0;int sym = 1;if(str[pos] == '+')pos++;else if(str[pos] == '-'){pos++;sym=-1;}int num =0;while(pos<str.length()){assert(str[pos]>='0');assert(str[pos]<='9');num = num*10+(str[pos]-'0');assert(num>=0);pos++;}num*=sym;return num;}int main(){string str = "-1024";int num = str_2_int(str);cout << num << endl;return 0;}

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.