1. Readability

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#import <cs50.h>
#import <stdio.h>
#import <string.h>
#import <stdlib.h>
 
int main(int argc, char *argv[]){
    int z;
 
    if(argc <= 1 || argc >= 3){
        printf("Usage: ./caesar key\n");
        return 1;
    } else if((z = atoi(argv[1])) == 0 ){
        printf("Usage: ./caesar key\n");
        return 1;
    }
    z = atoi(argv[1]);
    char *plaintext = get_string("plaintext: ");
 
    for(int i = 0, n = strlen(plaintext); i < n; i++){
        char letter = plaintext[i];
        //this prevents converting spaces and commas
        if(letter >= 'A'){
            int temp = z;
            //prevents inputs higher than 26
            while(temp > 26){
                    temp -= 26;
            }
            //for lower case that exceeds z
            if(letter + z > 'z'){
                if(letter + temp > 'z') {
                    temp -= ('z' - letter);
                    plaintext[i] = 'a' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //for capital letters that exceeds z
            } else if (letter + z > 'Z' && letter < 'a'){
                if(letter + temp > 'Z') {
                    temp -= ('Z' - letter);
                    plaintext[i] = 'A' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //if it is normal, just convert
            } else {
                plaintext[i] += z;
            }
        }
 
    }
    //print vowalla
    printf("ciphertext: %s\n", plaintext);
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

2. Caesar

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#import <cs50.h>
#import <stdio.h>
#import <string.h>
#import <stdlib.h>
 
int main(int argc, char *argv[]){
    int z;
 
    if(argc <= 1 || argc >= 3){
        printf("Usage: ./caesar key\n");
        return 1;
    } else if((z = atoi(argv[1])) == 0 ){
        printf("Usage: ./caesar key\n");
        return 1;
    }
    z = atoi(argv[1]);
    char *plaintext = get_string("plaintext: ");
 
    for(int i = 0, n = strlen(plaintext); i < n; i++){
        char letter = plaintext[i];
        //this prevents converting spaces and commas
        if(letter >= 'A'){
            int temp = z;
            //prevents inputs higher than 26
            while(temp > 26){
                    temp -= 26;
            }
            //for lower case that exceeds z
            if(letter + z > 'z'){
                if(letter + temp > 'z') {
                    temp -= ('z' - letter);
                    plaintext[i] = 'a' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //for capital letters that exceeds z
            } else if (letter + z > 'Z' && letter < 'a'){
                if(letter + temp > 'Z') {
                    temp -= ('Z' - letter);
                    plaintext[i] = 'A' - 1 + temp;
                } else {
                    plaintext[i] += temp;
                }
            //if it is normal, just convert
            } else {
                plaintext[i] += z;
            }
        }
 
    }
    //print vowalla
    printf("ciphertext: %s\n", plaintext);
}
 
 
 

2. Substitution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
 
char *encipher(char *t, char *argv[]);
bool validate_key(char *argv[]);
 
int main(int argc, char *argv[]){
 
    //Get key O
    //validate key O
        //check key length O
        //chekc for non-alphabetic characters O
        //check for repeated characters(case-insensitive) O
    //get plaintext O
    //encipher O
        //for each alphabetic character, determine what letter it maps to O
        //preserve case O
        //leave non-alphabetic characters as-is O
    //print ciphertext O
 
    //validates key's length and invalid keys
    if(!(argc > 1 && argc < 3)){
        printf("Usage: ./substitution key\n");
        return 1;
    } else if(!(validate_key(argv))) return 1;
 
    //get plaintext
    char *= get_string("plaintext: ");
 
    //encipher & print ciphertext
    printf("ciphertext: %s\n", encipher(t, argv));
}
 
bool validate_key(char *argv[]){
    //validate key
        //check key length
        //check for non-alphabetic characters
        //check for repeated characters(case-insensitive)
    char alphabet[] = {'A','B','C','D','E','F','G','H',
                    'I','J','K','L','M','N','O','P',
                     'Q','R','S','T','U','V','W','X','Y','Z'};
 
    //sets checkRepeat to all false;
    bool checkRepeat[strlen(argv[1])];
    for(int i = 0, n = strlen(argv[1]); i < n; i++){
        checkRepeat[i] = false;
    }
 
    //checks for key's length
    if(strlen(argv[1]) != 26){
        printf("Key must contain 26 characters.\n");
        return 0;
    }
 
    //checks for repeated value or incorrect value
    for(int i = 0, n = strlen(argv[1]); i < n; i++){
        if((argv[1][i] >= 'a' && argv[1][i] <= 'z'|| (argv[1][i] >= 'A' && argv[1][i] <= 'Z')){
            for(int j = 0, m = strlen(alphabet); j < m; j++){
                if(argv[1][i] == alphabet[j] || argv[1][i] - ('a' - 'A'== alphabet[j]){
 
                    if(!checkRepeat[j]) {
                        checkRepeat[j] = true;
                        printf("it entered here on %i\n", j);
                        break;
                    }else if (checkRepeat[j]){
                        printf("Key must not contain repeated characters.\n");
                        return 0;
                    }
                }
            }
        } else {
            printf("Key must only contain alphabetic characters.\n");
            return 0;
        }
    }
 
    //converts all lower case to upper case
    for(int i = 0, n = strlen(argv[1]); i < n; i++){
        if(argv[1][i] >= 'a') argv[1][i] -= ('a' - 'A');
    }
 
    return 1;
 
}
 
char *encipher(char *t, char *argv[]){
    //encipher
        //for each alphabetic character, determine what letter it maps to
        //preserve case
        //leave non-alphabetic characters as-is
 
    //stores inputted letter placement from the alphabet
    int a = strlen(t);
    int numbers[a];
    int upperLowerDifference = 'a' - 'A';
 
    //alphabet array to find out letter placement
    char alphabet[] = {'A','B','C','D','E','F','G','H',
                        'I','J','K','L','M','N','O','P',
                         'Q','R','S','T','U','V','W','X','Y','Z'};
 
    //stores letter placement into numbers array
    for(int i = 0; i < a; i++){
        for(int j = 0, z = strlen(alphabet); j < z; j++){
            if(t[i] == alphabet[j]) {
                numbers[i] = j;
                break;
            }else if(t[i] == alphabet[j] + upperLowerDifference){
                numbers[i] = j + upperLowerDifference;
                break;
            }
        }
    }
 
    //replaces plaintext into enciphered text
    for(int i = 0; i < a; i++){
        if((t[i] >= 'a' && t[i] <= 'z'|| (t[i] >= 'A' && t[i] <= 'Z')){
            if(numbers[i] >= upperLowerDifference ) t[i] = argv[1][numbers[i] - upperLowerDifference] + upperLowerDifference;
            else t[i] = argv[1][numbers[i]];
        }
    }
 
    return t;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'ETC' 카테고리의 다른 글

01/20/20 notes(mac java dw, java download and setup)  (0) 2020.01.20
Algorithms(week3, problemset)  (0) 2020.01.06
C Programming Language(week1, problem set)  (0) 2019.12.30
Memory (week3)  (0) 2019.12.27
Arrays and Sorting Algorithms (week2)  (0) 2019.12.26

https://cs50.harvard.edu/college/psets/1/

1. Hello

1
2
3
4
5
6
7
8
#include <stdio.h>
#include <cs50.h>
 
int main(void)
{
    string name = get_string("What is your name?\n");
    printf("hello, %s\n", name);
}
 

2a. Mario less

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <cs50.h>
#include <stdio.h>
 
int main(void)
{
    int stairs = get_int("Height: ");
    while(!(stairs >= 1 && stairs <= 8)) stairs = get_int("Height: ");
    for(int i = 0; i < stairs; i++){
        for(int j = stairs; j > i + 1; j--){
            printf(" ");
        }
        
        for(int j = 0; j <= i; j++){
            printf("#");
        }
        printf("\n");
    }
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

2b. Mario more

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <cs50.h>
#include <stdio.h>
 
int main(void)
{
    int stairs = get_int("Height: ");
    while(!(stairs >= 1 && stairs <= 8)) stairs = get_int("Height: ");
    
    for(int i = 0; i < stairs; i++){
        for(int j = stairs; j > i + 1; j--){
            printf(" ");
        }
        
        for(int j = 0; j < i + 1; j++){
            printf("#");
        }
        
        printf("  ");
        
        for(int j = 0; j < i + 1; j++){
            printf("#");
        }
        
        /*for(int j = stairs; j > i + 1; j--){
            printf(" ");
        }*/
        
        printf("\n");
    }
}
 
 

3a. Cash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <stdio.h>
#include <math.h>
#include <cs50.h>
 
int main(void){
    float change = get_float("Change owed: ");
    while(!(change >= 0.00)) change = get_float("Change owed: ");
    
    int coins = round(change * 100);
    
    int count = 0;
    while(coins != 0){
        if(coins >= 25){
            int temp = coins/25;
            coins = coins - (temp * 25);
            count += temp;
        }
        if(coins >= 10){
            int temp = coins/10;
            coins = coins - (temp * 10);
            count += temp;
        }
        if(coins >= 5){
            int temp = coins/5;
            coins = coins - (temp * 5);
            count += temp;
        }
        count += coins;
        coins = 0;
    }
    
    printf("%i\n", count);
}
 
 
 

3b. Credit

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#include <cs50.h>
#include <stdio.h>
 
int main(void){
    long number = get_long("Number: ");
    char *answer = NULL;
    
    if((number/1000000000000 > 1 && (number/1000000000000) % 10 == 4||
      (number/1000000000000000 > 1 && (number/1000000000000000) % 10 == 4)) {
        
        answer = malloc(5 * sizeof(char));
        answer = "VISA";
    }
    else if((number/100000000000000> 1 && 
            ((number/10000000000000) % 100 == 34 || (number/10000000000000) % 100 == 37)){
       
        answer = malloc(5 * sizeof(char));
        answer = "AMEX";
    } 
    else if((number/100000000000000> 1 && 
            ((number/100000000000000) % 100 >= 51 && (number/100000000000000) % 100 <= 55)) {
        
        answer = malloc(10 * sizeof(char));
        answer = "MASTERCARD";
        printf("master?\n");
    } else {
        printf("INVALID\n");
        return 0;
    }
    
    int forSum = 0;
    for(long i = 10; i <= number; i *= 100){
        int divNum = ((number % (i * 10))/i) * 2;
        if(divNum >= 10){
            int temp = divNum % 10;
            divNum /= 10;
            forSum += temp + divNum;
        } else {
            forSum += divNum;
        }
        //printf("%i, %ld forSum, %i\n", forSum, i, divNum);
    }
    
    int restSum = 0;
    for(long i = 10; i <= number * 10; i *= 100){
        int restNum = (number % (i))/(i/10);
        restSum += restNum;
        //printf("%i, %ld restSum, %i\n", restSum, i, restNum);
    }
    if((forSum + restSum) % 10 == 0){
        printf("%s\n", answer);
    } else {
        printf("INVALID\n");
    }
    
}
 
 

'ETC' 카테고리의 다른 글

Algorithms(week3, problemset)  (0) 2020.01.06
Arrays(week 2, problem set)  (0) 2019.12.30
Memory (week3)  (0) 2019.12.27
Arrays and Sorting Algorithms (week2)  (0) 2019.12.26
C Programming Language(week 1)  (0) 2019.12.25

Compiling contains four steps, preprocessing, compiling, assembling and linking.

First convert a source code into required functions, like for instance in c, read hashtags and copy and past files.

Second step is compiling, convert source code into assembling codes.

Third step is assembling, converting assembling codes into machine codes, 1s and 0s.

Last, link all files into 0s and 1s.

 

Programmers don’t like to be tedious all the times, instead use powerful tools to assist them when programming. From cs50 sandbox, we will now use cs50 ide(integrated development environment)

 

 

Terminal commands

Ls – shows list of files in current location

Cd – redirect current location(cd .. for back, cd filename to go to that directory)

Rm – to remove a file

Mkdir – makes folder

Rmdir – removes directory

Make – creates a runnable code

./ - runs the source code

Touch – creates a file

 

 

Utilize the power of a debugger! Will save you minutes and hours with a problem.

String is actually an array of characters with null at the back.


0x0 is null! Could be seen at debugger

Data type can only receive certain size of a byte. String returns memory location.

 

brian returns 100th value in memory while veronica returns 900th value in memory.

 

String is a synonym of char *. * means an address of a something to its left, char * will mean character’s address. A pointer is an address.

 

When nothing is specified in the main function, it automatically returns 0 if it runs successfully.

 

Segmentation fault means user touched memory that user should not have. Returning one if null like above helps to prevent memory problems.

 

Difference in size of Char:

 

Since C only supports ASCII (English), 1 byte is enough for char (256 characters; 0 to 255). Since Java supports more than 18 international languages with over 3200 characters, a char variable is assigned a space of 2 bytes (2^16 = 65536 characters). 

 

 

CS50 IDE

1. comparing strings

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <cs50.h>
#include <stdio.h>
#include <string.h>
 
bool compare_strings(char *a, char *b);
 
int main(void){
    char *= get_string("enter i : ");
    if(i == NULLreturn 1;
    char *= get_string("enter j : ");
 
    //null and exclamation point is the same thing
    if(!j) return 1;
 
    if(compare_strings(i,j)) printf("same\n");
    else printf("not same\n");
 
    //strcmp returns 0 if it's equal + if i comes before j
    //- if j comes before i, a function provided by string.h
    if(strcmp(i,j) == 0printf("itworks!\n");
 
    return 0;
}
 
bool compare_strings(char *a, char *b){
    int alength = strlen(a);
    int blength = strlen(b);
 
    if(alength != blength) return false;
 
    for(int i = 0; i < alength; i++){
        if(a[i] != b[i]) return false;
    }
 
    return true;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

compares strings if it is same or not. The key point is the run about pointers and how * works. 

 

2. String? address?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
 
//receive user input and capitalize the first letter of a given word
int main(void){
    /*char *c = get_string("type your word : ");
 
    for(int i = 0; i < strlen(c); i++){
        printf("%c : %i\n", c[i], c[i]);
    }
 
 
    if(c[0] >= 'a' && c[0] <= 'z') c[0] = c[0] - ('a' - 'A');
    printf("%s\n",c);*/
 
    string s = get_string("type your word : ");
 
    string t = s;
 
    if(strlen(t) > 0) t[0= toupper(t[0]);
 
    printf("s : %s\n", s);
    printf("t : %s\n", t);
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

~/ $ cd memory

~/memory/ $ make copy0

clang -ggdb3 -O0 -std=c11 -Wall -Werror -Wextra -Wno-sign-compare -Wno-unused-parameter -Wno-unused-variable -Wshadow copy0.c -lcrypt -lcs50 -lm -o copy0

~/memory/ $ ./copy0

type your word : taewon

s : Taewon

t : Taewon

~/memory/ $

 

I only changed t but is applied to s as well. Learning about address concept. 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#include <stdio.h>
#include <cs50.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
 
//receive user input and capitalize the first letter of a given word
int main(void){
 
    char *= get_string("type your word : ");
 
    //malloc stands for memory allocate
    //malloc creates a room and have to specify how many byte is required
    //for the given room
    //get the size of s, if it is david the size is 5.
    //+1 is required because compiler stops reading the memory until \0 appears
    //now for each space how many byte is required.
    //char is 1byte in C, ONLY in C because english was only used
    //since char is 1byte, sizeof is really not necessary but wrote it
    //for specification
    char *= malloc((strlen(s) + 1* sizeof(char));
 
    strcpy(t, s);
   /* for(int i = 0, n = strlen(s); i <= n; i++){
        t[i] = s[i];
    }*/
 
    if(strlen(t) > 0) t[0= toupper(t[0]);
    printf("s : %s\n", s);
    printf("t : %s\n", t);
 
    //to avoid memory leak!
    free(t);
 
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

To copy and change the value, malloc is used. Malloc means memory allocate, first we need to assign a memory size to a given variable. Since string is value + null, string length + 1 is needed to used first and we need to multiple by the data type size. Char in c is 1 byte, unlike 2 byte in java because it only supports english. since multiplying by 1 is returning itself, sizeof char is not really needed for this situation but will include it since it is more precise. 

 

Copying a value to another string(char *), we could use a for loop or a function c provides with string, a strcpy. 

When t is only used here once, we free the t to avoid memory leak.

 

3. scanning

1
2
3
4
5
6
7
8
9
10
11
12
#include <stdio.h>
 
int main(void){
    int x;
    printf("x : ");
    //scanf requires the address of the variable so ampersand is used &
    //ampersand means the address of that variable
    //if it's a string(char*), ampersand is not used because already an
    //address is given
    scanf("%i"&x);
    printf("x : %i\n", x);
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

ampersand gets the address while star uses that address!

 

4.  let us see address!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <cs50.h>
#include <stdio.h>
 
int main(void){
    char *= get_string("s: ");
    char *= get_string("t: ");
 
    printf("s: %p\n", s);
    printf("t: %p\n", t);
 
    //0x17686b0
    //0x means anything that comes after 0x is hexadecimal
    //17686b0 is hexadecimal, represented for memory location
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

~/memory/ $ ./addressess
s: taewon
t: weeee
s: 0x865670
t: 0x8656b0
~/memory/ $ 

 

5. swapping? use stars to apply address!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <stdio.h>
 
void swap(int *a, int *b);
 
int main(void){
    int a = 1;
    int b = 2;
 
    printf("a is %i, b is %i\n", a, b);
    swap(&a, &b);
    printf("a is %i, b is %i\n", a, b);
 }
 
//* means address!!
//& means give me address of that value, * means go to that address of that value! different
void swap(int *a, int *b){
    int temp = *a;
    *= *b;
    *= temp;
}
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

 

 

Preprocessing – #include <stdio.h>

Compiling - programming language converts codes to assembly language for computer to understand

Assembling – using assembling code and converts to 10101010100101001010s(machine code, object code)

Linking – linking step links all the imported files, stdio.h + cs50.h + yourfile.h.

at step linking, converting all imported files into machine code and about to link them together

These days, people call these four steps compiling to be general.

 

Ram, random access memory, only runs when electricity is being charged to the device. This is the place where all the programs store memory temporary, copying the data from physical storage device and pasting it to ram. Much faster to access file from ram than from physical storage space every time you access a file.

 

Continuous memory is represented as an array. Array helps design wise and helps sufficiency.  

Printing one character at a time

 

Capitalizing all characters

 

Printing ascii per character
Prints typed arguments including program name and types all character of that argument

 

using returns

Main contains return key, just implicitly. For example, when an error occurs, a number might appear like -27, a programmer has defined the error as return -27 for that certain problem.

 

Sorting Algorithms

 

Bubble sort – repeatedly swapping the adjacent element if they are in the wrong order. For every turn, the searching size will decrease from the last place of an array.

 

Selection sort – repeatedly finding the minimum element from unsorted order. For every turn, the first place of an array increases.

How O(n^2)is calculated
Beautiful time complexity graph

Merge sort - a divide and conquer algorithm, it divides the array in two halves, and if the array is sorted, it merges with sorted arrays. O(n log n)

 

Insertion sort, gnome sort both have O(n^2) time complexity.

 

Now a day, computers are performing billions of things in a second gigahertz speed, a more readable code is more preferred in some cases.

 

Input | Source code – code we humans have written using java, c, python

              Compiler

Output | Machine code – 0 and 1s

 

Ram – temporary storage, has finite number of transistors which means there are finite of values that can be represented and stored accurately. For example, when you divide a number and add 50 more decimal place holders, the number that is displaced is imprecision, very micro value but still imprecision. For this reason finance displays dollars up to the thousands place, because back in the days when this was not obvious, people made money by adding up penny values.

 

When value reaches its’ max value, it overflows and returns to the beginning.

Cs50 sandbox

 

 

Computer science is about problem solving

 

           H              I (letter ascii)

          72             73 (decimal numbers)

      1001000        1001001 (binary 8 bit)

 

Abstraction – converting lower level details into more simplified version and focus on problem solving

Since there are so many languages that cannot be represented by 8 bit(256 different type of possibilities), now we use Unicode or utf-8 which uses 16 bit(2 to 16th power or 65536 different possibilities).

 

Rgb – a dot, pixel, uses three byte per pixel, how many red, how many green, how many blue per pixel.

An image is a group of pixels using three bytes(24 bit) in total of kilobytes, megabytes, and so fourth.

A video is a collection of images, 24 fps(frames per second) example, showing 24 images per second, showing a sequence of static images and makes it look like a moving video.

Videos -> images -> colors -> bits -> frequency of electricity

 

Input -> algorithms -> output 

Pseudo code – a simplified programming language

 verbs here are functions, questions like if else if are conditions, smith is among names is Boolean expression, go back to step2 loops

Gigahertz – GHz is a unit of measurement for AC(alternating current) or em(electromagnetic) wave frequencies equal to one billion hertz.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 
public class Main {
    //3
    //8
    //10
    //16
    
    //result 
    //3 5
    //5 5
    //5 11
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        
        int repeat = Integer.parseInt(br.readLine());
        
        while(repeat > 0) {
            repeat--;
            int n = Integer.parseInt(br.readLine());
            boolean[] bool = new boolean[n];
            //sieve of Eratosthenes or 에라토스테네스의 체
            //모든 숫자를 true값을 지정해준다
            for(int i = 2; i < bool.length; i++) {
                bool[i] = true;
            }
            //eratosthenes 알고리즘으로 소수 아닌 숫자들은 false
            //처음으로 2의배수, 그리고 3의배수, 4의배수 다음 5의배수, n의 제곱근까지
            for(int i = 2; i < Math.sqrt(n); i++) {
                if(bool[i]) {
                    for(int j = i * i; j < n; j += i) {
                        bool[j] = false;
                    }
                }
            }
            //중간부터 시작
            int firstIndex = n/2;
            int secondIndex = n/2;
            
            while(true) {
                if(bool[firstIndex] && bool[secondIndex]) break;
                firstIndex --;
                secondIndex ++;
            }
 
            bw.write(String.valueOf(firstIndex) + " " + String.valueOf(secondIndex) + "\n");
        
        }
        bw.flush();
    }
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

remains unsolved number theory, goldbach's conjecture

'알고리즘' 카테고리의 다른 글

백준 9단계(4948)  (0) 2019.12.22
백준 9단계(1929)  (0) 2019.12.22
백준 9단계(2581)  (0) 2019.12.22
백준 9단계(1978)  (0) 2019.12.21
백준 8단계(1011)  (0) 2019.12.21
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
 
public class Main {
    
    //1
    //10
    //13
    //100
    //1000
    //10000
    //100000
    //0
    
    //result
    
    //1
    //4
    //3
    //21
    //135
    //1033
    //8392
    public static void main(String[] args) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    
        //n이 0이 입력될때까지 반복 처리
        int n;
        while((n = Integer.parseInt(br.readLine())) != 0){
            
            //sieve of eratosthenes
            boolean[] bool = new boolean[2 * n + 1];
            for(int i = 1; i < bool.length; i++) {
                bool[i] = true;
            }
            
            for(int i = 2; i < Math.sqrt(bool.length) ; i++) {
                if(bool[i]) {
                    for(int j = i * i; j < bool.length; j += i) {
                        bool[j] = false;
                    }
                }
            }
            //시작 번호 + 1을해서 처리를 해야한다, 그 이유는 13을 입력했을때 
            //시작 번호를 포함하면 4개 소수이지만 포함을 안하면 3개 소수를 출력한다
            int cnt = 0;
            for(int i = n + 1; i <= 2*n; i++) {
                if(bool[i]) cnt++;
            }
            bw.write(String.valueOf(cnt) + "\n");
            
        }
        bw.flush();
    }
    
}
 
http://colorscripter.com/info#e" target="_blank" style="color:#e5e5e5text-decoration:none">Colored by Color Scripter
 

'알고리즘' 카테고리의 다른 글

백준 9단계(9020)  (0) 2019.12.22
백준 9단계(1929)  (0) 2019.12.22
백준 9단계(2581)  (0) 2019.12.22
백준 9단계(1978)  (0) 2019.12.21
백준 8단계(1011)  (0) 2019.12.21

+ Recent posts