unsigned long init_sieve(unsigned long max_n) { size_t is_p_sz = max_n / (2 * ULONG_SZ) + 1; numtheory_is_prime = malloc(is_p_sz * ULONG_SZ); memset(numtheory_is_prime, 0xFFFFFFFF, is_p_sz * ULONG_SZ); unset_bit(numtheory_is_prime, 1); numtheory_primes = calloc((long)((double)max_n/(log((double)max_n)-4.0)+1), ULONG_SZ); unsigned long j; unsigned long p = 0; numtheory_primes[p++] = 2; numtheory_primes[p++] = 3; unsigned LONG_LONG i1, i2, s; unsigned long max_n_sqrt = (unsigned long)(sqrt((double)max_n)); for (i1 = 5, i2 = 7; ; i1 += 6, i2 += 6) { if (i1 > max_n_sqrt) break; if (is_set(numtheory_is_prime, i1)) { s = i1 << 1; for (j = i1 * i1; j <= max_n; j += s) unset_bit(numtheory_is_prime, j); numtheory_primes[p++] = i1; } if (i2 > max_n_sqrt) break; if (is_set(numtheory_is_prime, i2)) { s = i2 << 1; for (j = i2 * i2; j <= max_n; j += s) unset_bit(numtheory_is_prime, j); numtheory_primes[p++] = i2; } } for ( ; ; i1 += 6, i2 += 6) { if (i1 > max_n) break; if (is_set(numtheory_is_prime, i1)) numtheory_primes[p++] = i1; if (i2 > max_n) break; if (is_set(numtheory_is_prime, i2)) numtheory_primes[p++] = i2; } numtheory_primes = realloc(numtheory_primes, p * ULONG_SZ); return p; }
void Sievelng<longint>::eratosthene() { int p; int ip = K+1; // Le rang du premier premier non precrible int64 sqrt_B = root(B); // QUEL SQRT cerr << "size of sqrt_B = " << sizeof(sqrt_B) << endl; if (sqrt_B > max_prime()) { cerr << "Dans eratoshene,,, : pas assez de nombres premiers\n"; cerr << "SQRT_B = " << sqrt_B << " maxp = " << max_prime() << "\n"; cerr << "Crible aux. pour enumerer les premiers manquants " << endl; // auxprimes.setup(100000020,MAX64); cerr <<" SIZE == " << SIZE << endl; int szx; if (SIZE > INT_MAX) szx = 2000000010; else szx = SIZE; cerr << "szx = " << szx << endl; auxprimes.setup(szx,MAX64); auxprimes.set_at_left(max_prime()); auxprimes.eratosthene(); cerr << "auxprime eratosthene is done" << endl; auxprimes.set_cursor_on(max_prime()); cerr << "auxprime cursor is on maxprime() = " << auxprimes.current_prime() << endl; int64 p = auxprimes.next_prime(); cerr << "Premier nombre premier complementaire " << p << endl; } if (A <= 1) unset_bit(0); p = prime(ip++); cerr << "Crible 1 jusqu'a p= " << min(sqrt_B,max_prime()) << endl; cerr << "premier p = " << p << endl; while (p <= min(sqrt_B,max_prime())) { //cerr << "sieve by " << p << endl; sieve_by(p); if (A <= p){ // Il est de toute facon <= LMAX set_bit(index(p)); } p = prime(ip++); } int cnt = 0; if (sqrt_B > max_prime()) { cerr << "Crible complementaire " << endl; int64 p = auxprimes.current_prime(); while (p <= sqrt_B) { cnt++; if (p > SIZE) sieve_by_long(p); else sieve_by(p); p = auxprimes.next_prime(); } cerr << "Fin du crible complementaire" << endl; } cursor = 0; #if SIEVE_LNG_VERBOSE > 0 cerr << "Nombre de premiers complementaires = " << cnt << endl; #endif }
int add_block_in_inode(struct ext2_inode *current_inode, char *block_bitmap, unsigned int inode_num){ unsigned int new_inode_block_index = (current_inode -> i_size > 0)? ((((current_inode -> i_size) - 1) >> 10) + 1) : 0; if (new_inode_block_index >= 1024+12) { return -1; } int new_block = find_last_free_bit(block_bitmap, 128); if(new_block == -1){ return -1; } set_bit(block_bitmap, new_block); if (new_inode_block_index <= 12) { current_inode -> i_block[new_inode_block_index] = new_block + 1; set_bit(block_bitmap, new_block); } if(new_inode_block_index == 12) { new_block = find_first_free_bit(block_bitmap, 0, 128); if(new_block == -1){ unset_bit(block_bitmap, current_inode -> i_block[12] - 1); return -1; } } if(new_inode_block_index >= 12) { unsigned int *indirect_pointer_block = (unsigned int*) get_block(disk, current_inode -> i_block[12], 1024); indirect_pointer_block[new_inode_block_index - 12] = new_block + 1; set_bit(block_bitmap, new_block); } current_inode -> i_size += 1024; current_inode -> i_blocks += 2; return new_block + 1; }
void _kbfun_modifier_press_release(keycode key, bool is_pressed) { if (is_pressed) { set_bit(keyboard_modifier_keys, key); } else { unset_bit(keyboard_modifier_keys, key); } }
/* restore the previous signal mask */ void mutt_unblock_signals(void) { if (bit_val(options, OPTSIGNALSBLOCKED)) { sigprocmask(SIG_UNBLOCK, &Sigset, 0); unset_bit(options, OPTSIGNALSBLOCKED); } }
int main (void) { clunet_init(); clunet_set_on_data_received(data_received); time_init(); sei(); //eeprom_write_dword((void*)0, 0); record_num = eeprom_read_dword((void*)0); // Читаем кол-во записей mode_current = eeprom_read_byte((void*)4); // Режим mode_temp = eeprom_read_byte((void*)5); // Временный режим disk_initialize(0); unset_bit(DDRA, 3); set_bit(PORTA, 3); // Определение сигнала в линии //unset_bit(DDRA, 4); unset_bit(PORTA, 4); // Открывалка двери, напрямую set_bit(DDRA, 4); unset_bit(PORTA, 4); // Открывалка двери, через реле set_bit(DDRA, 5); HANGUP; // Реле снимания трубки set_bit(DDRA, 6); MODE_NORMAL; // Реле выбора режима unset_bit(DDRG, 0); set_bit(PORTG, 0); // Определение, лежит ли трубка set_bit(DDRD, 6); set_bit(DDRD, 7); // Светодиоды unset_bit(DDRA, 7); set_bit(PORTA, 7); // Счётчик оборотов диска unset_bit(DDRF, 0); // ADC+ unset_bit(PORTF, 0); unset_bit(DDRF, 1); // ADC- unset_bit(PORTF, 1); beep(500, 200); beep(1500, 200); beep(3000, 200); _delay_ms(1000); if (play_wav_pgm(STARTED_WAV) == 0) { LED_GREEN_ON; while (sound_read() >= 0) ; LED_GREEN_OFF; sound_stop(); } else { LED_RED_ON; beep(3000, 200); beep(1500, 200); beep(500, 200); LED_RED_OFF; } send_current_mode(CLUNET_BROADCAST_ADDRESS); while(1) { if (is_LINE_POWER()) incoming_ring(); if (OFFHOOK) control_mode(); transfer_data(); // Передаём данные на досуге. } }
void Sievelgmp::eratosthene() { cout << "In eratosthene A = " << A << " B = " << B << endl; int p; int ip = K+1; // Le rang du premier premier non precrible int64 sqrt_B = root(B); // QUEL SQRT cout << "sqrt_B = " << sqrt_B << endl; if (sqrt_B > max_prime()) { cout << "Dans eratoshene : pas assez de nombres premiers\n"; // cout << "SQRT_B = " << sqrt_B << " maxp = " << max_prime() << "\n"; cout << "Crible aux. pour enumerer les premiers manquants " << endl; auxprimes.setup(100000020,MAX64); auxprimes.eratosthene(); auxprimes.set_cursor_on(max_prime()); int64 p = auxprimes.next_prime(); cout << "auxprime current prime " << p << endl; } if (A <= 1) unset_bit(0); p = prime(ip++); cout << "Crible 1 jusqu'a p= " << min(sqrt_B,max_prime()) << endl; while (p <= min(sqrt_B,max_prime())) { sieve_by(p); //cout << "sieve by " << p << endl; if (A <= p){ // Il est de toute facon <= LMAX set_bit(index(p)); } p = prime(ip++); } int cnt = 0; if (sqrt_B > max_prime()) { cout << "Crible complementaire " << endl; int64 p = auxprimes.current_prime(); while (p <= sqrt_B) { cnt++; // cout << "Crible par p p = " << p << endl; if (p > SIZE) sieve_by_long(p); else sieve_by(p); p = auxprimes.next_prime(); } cout << "Fin du crible complementaire" << endl; // cout << "p = " << p << endl; } cursor = 0; #if SIEVE_LNG_VERBOSE > 0 cout << "Apres eratosthene : \n"; cout << "Nombre de premiers complementaires = " << cnt << endl; #endif }
void Sievelng<longint>::sieve_by_long(int64 p) { //cout << "sieve_by_long p = " << p << endl; qs = B; qs /= p; int r = (qs % 30); if ((r % 2 == 0) || (r % 3 == 0) || (r % 5) == 0) return; qs*=p; // qs est le plus grand multiple de p ne depassant pas B if(A < qs) { unset_bit(index(qs)); } }
/** * nfexp_attr_unset - unset a certain attribute * \param type attribute type * \param exp pointer to a valid expectation object * * On error, -1 is returned and errno is set appropiately, otherwise * 0 is returned. */ int nfexp_attr_unset(struct nf_expect *exp, const enum nf_expect_attr type) { assert(exp != NULL); if (type >= ATTR_EXP_MAX) { errno = EINVAL; return -1; } unset_bit(type, exp->set); return 0; }
void free_inode(struct ext2_inode *current_inode, void *disk, char *blockbitmap){ unsigned int i_size = current_inode->i_size; unsigned int blocks = (i_size > 0)? ((i_size-1) / 1024) + 1: 0; int block = 0; for(block=0; block<blocks; block++){ //free's indirect blocks if(block>=12){ unsigned int* indirect_pointer_block = (unsigned int *) get_block(disk, current_inode->i_block[12], 1024); //indirect_pointer_block [inode_index - 12] = block_number; unset_bit(blockbitmap, indirect_pointer_block[block - 12] - 1); //free(indirect_pointer_block[block - 12]); }else{ //free's direct blocks unset_bit(blockbitmap, current_inode->i_block[block] - 1); //free(current_inode->i_block[block-1]); } } if(blocks > 12){ unset_bit(blockbitmap, current_inode->i_block[12] - 1); } }
void fungus::die() { // extern vector<string> message; set_bit(attributes, DEAD); set_bit(attributes, KILL_ME); if(range(0,5)==0) for(unsigned int i=0; i<curr_level->monsters.size(); i++) if(curr_level->monsters[i]->type == type && curr_level->monsters[i]->x >= x-1 && curr_level->monsters[i]->x <= x+1 && curr_level->monsters[i]->y >= y-1 && curr_level->monsters[i]->y <= y+1) { unset_bit(curr_level->monsters[i]->attributes, ASLEEP); curr_level->monsters[i]->energy = curr_level->guy->speed; curr_level->monsters[i]->other_count = 0; } }
void Sievelgmp::sieve_by_long(int64 p) { // cout << "sieve_by_long p = " << p << endl; qs = B; qs /= p; int r = (qs % 30); if ((r % 2 == 0) || (r % 3 == 0) || (r % 5) == 0) return; qs*=p; // qs est le plus grand multiple de p ne depassant pas B if(A < qs) { // cout << "On supprime " << qs << endl; unset_bit(index(qs)); } else { //cout << "Pas de multiple de p dans l'intervalle courant" << endl; // cout << "p = " << p << endl; } }
void deallocate(void *data) { int offset, current_bit, current_short; // aus pointer offset berechnen offset = (((long)data - (long)(&arena[0]))/BLOCKSIZE); // printf("[debug] offset: %d - %d / size = %d\n", (int)data, (int)(&arena[0]), offset); // short und bit bestimmen current_bit = offset % 16; current_short = (offset - current_bit) / 16; // bit unsetten unset_bit(&allocated_map[current_short], current_bit); printf("[info] deallocated block: %d/%d [%ld]\n", current_short, current_bit, (long)(&arena[offset*BLOCKSIZE])); }
void Sievelgmp::sieve_by(int64 p) { int64 q = inversePK64(p);// De l'ordre de grandeur de p int64 increment = FK*p; int64 debut = 0; tmp1 = A; tmp1-= 1; remdivlong64(debut,tmp1,p); //debut =(A-1)%p de l'ordre de grandeur de p for (int k=0; k < FK; k++) { int64 i0 = q*(debut+CLASS[k]) % p; if (i0) i0 = p-i0; int64 ibase = k + FK*i0; for (int64 i = ibase ; i <= max_bit_index ; i += increment) unset_bit((int)i); } }
int main(int argc, char **argv){ if(argc != 3) { fprintf(stderr, "Usage: ext2_ls <image file name> <absolute path on the disk>\n"); exit(1); } int fd = open(argv[1], O_RDWR); disk = mmap(NULL, 128 * 1024, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); if(disk == MAP_FAILED) { perror("mmap"); exit(1); } char *abs_path = argv[2]; if (abs_path[0] != '/') { fprintf(stderr,"Not an Absolute Path" ); exit(1); } char *dir[100]; int length=0; char *tok = strtok(abs_path, "/"); while (tok != NULL) { dir[length]= tok; length++; tok = strtok(NULL, "/"); } blockgd = (struct ext2_group_desc *)(disk + 1024 + (EXT2_BLOCK_SIZE)); inodeTable = (struct ext2_inode *)(disk + (blockgd->bg_inode_table * (EXT2_BLOCK_SIZE))); int inode = 1; int i; for (i = 0; i< length-1; i++) { inode = find_inode(dir[i], inode); if (inode == -1) { fprintf(stderr, "no such directory\n"); exit(ENOENT); } } struct ext2_inode dirInode = inodeTable[inode]; int fileInode = -1; int shift=0; for(i=0;i<dirInode.i_blocks/2;i++){ if(fileInode!=-1){ break; } struct ext2_dir_entry_2 *entry; if(i>=12){ entry = (struct ext2_dir_entry_2 *)(disk + (((unsigned int *)(disk + (inodeTable[inode].i_block[12] -1) * (EXT2_BLOCK_SIZE)))[i-12] -1)*EXT2_BLOCK_SIZE); }else{ entry = (struct ext2_dir_entry_2 *)(disk + inodeTable[inode].i_block[i] * (EXT2_BLOCK_SIZE)); } struct ext2_dir_entry_2 *prev; while (shift < EXT2_BLOCK_SIZE) { char name[entry->name_len]; int n; for(n= 0; n < entry->name_len; n++) { name[n]=entry->name[n]; } name[entry->name_len] ='\0'; if (entry->file_type == 1 && strcmp(dir[length - 1], name) == 0) { fileInode = entry->inode -1; // -1 cause position in the inode table if(prev){ prev->rec_len += entry->rec_len; } break; } else { shift=shift + entry->rec_len; prev = entry; entry = (struct ext2_dir_entry_2 *)(disk + inodeTable[inode].i_block[i] * (EXT2_BLOCK_SIZE)+ shift); } } } if(fileInode!=-1){ struct ext2_inode fileInodeStruct = inodeTable[fileInode]; int j; for(j=0;j<fileInodeStruct.i_blocks/2;j++){ int blockID; if(j>=12){ blockID = (disk + (fileInodeStruct.i_block[12] -1)*EXT2_BLOCK_SIZE)[j-12] -1; }else{ blockID = fileInodeStruct.i_block[j] - 1; } unset_bit(blockgd->bg_block_bitmap, blockID); } unset_bit(blockgd->bg_inode_bitmap, fileInode); }else{ printf("no such file"); exit(ENOENT); } return 0; }
int main(){ //taking input in hex char * hex = (char *)malloc(sizeof(char)* 20); scanf("%s", hex); printf("%s\n", hex); int a; sscanf(hex,"%x",&a); int input_length = no_of_bits(a); print_binary(a); // printf("%d\n", r(a)); int nbits = no_of_bits(a); int rval = r(nbits); printf("rval is%d\n",rval); int msg = power_2(rval+nbits)- 1; int msg_length = rval+nbits; int i; int p_index = 0; int p; while(1){ p = power_2(p_index); if (p >= (msg_length)) break; unset_bit(&msg, p,(msg_length)); printf("%d\n",p); p_index++; } printf("After setting the parity bits to 0\n"); print_binary(msg); int j = 1; for(i = 1; i<= input_length; i++){ while(check_bit_left(msg, j,msg_length) == 0) j++; printf("j is %d\n", j); if(check_bit_left(a, i, input_length)) set_bit(&msg, j, msg_length); else unset_bit(&msg, j, msg_length); j++; } printf("After setting the input bits\n"); print_binary(msg); printf("Checking bit 1 %d\n",check_bit_left(msg,1, msg_length) ); p_index = 0; while(1){ p = power_2(p_index); if (p > (msg_length)) break; printf("p is %d\n", p); int x= p; int c; int count= 0;//count for 1's in bit representaion while(1){ // printf("x is %d\n", x); if(x > msg_length) break; for(c = 0; c <p;c++){ if(x > msg_length) break; printf("Checking %d\n", x); if (check_bit_left(msg,x, msg_length)) count++; x++; } for(c = 0; c<p;c++){ x++; } } printf("Count for p = %d is %d \n",p, count ); if (count %2 != 0){// if odd, need to add 1 to set it for even parity set_bit(&msg, p, msg_length); } // unset_bit(&msg, p,(msg_length)); // printf("%d\n",p); p_index++; } printf("After correcting the parity bits\n"); print_binary(msg); printf("THis is the hamming code you have to send\n"); printf("%x\n", msg); int e; // printf("Enter a sample bit position to change to test for error correction\n"); // scanf("%d", &e); e = 7; int sample_error = msg; if (check_bit_left(sample_error, e, msg_length)) unset_bit(&sample_error, e, msg_length); else set_bit(&sample_error, e, msg_length); printf("Before correcting error\n"); print_binary(sample_error); p_index = 0; int error_index = 0; while(1){ p = power_2(p_index); if (p > (msg_length)) break; // printf("p is %d\n", p); int x= p; int c; int count= 0;//count for 1's in bit representaion while(1){ // printf("x is %d\n", x); if(x > msg_length) break; for(c = 0; c <p;c++){ if(x > msg_length) break; // printf("Checking %d\n", x); if (check_bit_left(sample_error,x, msg_length)) count++; x++; } for(c = 0; c<p;c++){ x++; } } // printf("Count for p = %d is %d \n",p, count ); if (count %2 != 0){// if odd, need to add 1 to set it for even parity error_index += p; } // unset_bit(&msg, p,(msg_length)); // printf("%d\n",p); p_index++; } if (check_bit_left(sample_error, error_index, msg_length)) unset_bit(&sample_error, error_index, msg_length); else set_bit(&sample_error, error_index, msg_length); printf("After correcting error\n"); print_binary(sample_error); printf("error index is %d\n", error_index); }
int main(int argc, char *argv[]) { int callrun; #ifdef MTRACE_DEBUG mtrace(); #endif /* Start initialisation:*/ /* Pick out the number from the string "$Revision: 2.37 $":*/ {/*Block begin*/ char *tmp=currentrevision; for( tmp=currentrevision;(*tmp!=' ')&&(*tmp!='\0');tmp++); if(*tmp == ' ') tmp++; for( currentRevisionNumber=tmp;(*tmp!=' ')&&(*tmp!='\0');tmp++); *tmp='\0'; }/*Block end*/ /* Check here is there the request for the version information. * If so, output the revision number and quit, if there are no any * other option: */ for(i=1; i<argc; i++) if( (s_cmp(argv[i],"-V")==0)||(s_cmp(argv[i],"-version")==0)){ printf("%s\n",currentRevisionNumber); if(argc == 2) exit(0); } first_init();/*module init.c*/ read_command_line(argc, argv);/*module cmd_line.c*/ message(INITIALIZATION,NULL); /*End initialisation*/ message(READINGCONFIG,config_name); scaner_init(config_name,cnf_comment);/*module init.c*/ read_config_file_before_truns();/*module cnf_read.c*/ if( is_bit_set(&mode,bitCHECKMOMENTABALANCE)&& (!is_bit_set(&mode,bitONLYINTERPRET)) ){ check_momenta_balance_on_each_topology(); } message(DONE,NULL); /*Translation of the TM program:*/ {char tmp[MAX_STR_LEN]; if ( (is_bit_set(&mode,bitONLYINTERPRET))|| (!is_bit_set(&mode,bitBROWS))|| (is_bit_set(&mode,bitVERIFY))|| (is_bit_set(&mode,bitFORCEDTRUNSLATION)) ){ command_init();/*module truns.c*/ if(!is_bit_set(&mode,bitONLYINTERPRET)){ if (set_table==NULL)set_table=create_hash_table( set_hash_size,str_hash,str_cmp,c_destructor); if(is_bit_set(&mode,bitBROWS)) install(new_str("_specmode"),new_str("browser"),set_table); else install(new_str("_specmode"),new_str("common"),set_table); } message(BEGINTRUNS,NULL); do{ if(truns(¤t_number_of_trunslated_lines, ¤t_array_of_trunslated_lines)){ number_of_trunslated_lines= current_number_of_trunslated_lines; current_number_of_trunslated_lines=0; array_of_trunslated_lines= current_array_of_trunslated_lines; current_array_of_trunslated_lines=NULL; } }while(number_of_trunslated_lines==0); message(ENDTRUNS,NULL); mem_esc_char=esc_char; macro_done();/*module macro.c*/ reject_proc();/*module truns.c*/ command_done();/*module truns.c*/ clear_defs();/*module truns.c*/ clear_label_stack();/*module truns.c*/ for_done();/*module truns.c*/ IF_done();/*module truns.c*/ if(s_scmp(sc_get_token(tmp),"translate")) halt(UNEXPECTED ,tmp); } } sc_done();/*module tools.c*/ /*TM program is translated. The resulting code is in array_of_trunslated_lines*/ /*Keep the table up to the end of the program!:*/ #ifdef SKIP if (vectors_table!=NULL){ hash_table_done(vectors_table);/*module hash.c*/ vectors_table=NULL; } #endif message(DONEINIT,NULL); if (is_bit_set(&mode,bitVERIFY)){ message(ONLYVERIFY,NULL); errorlevel=0;halt(NOERROR,NULL); } if (g_ttnames != NULL){/*Topology tables were defined in the config file*/ HASH_TABLE wrktrans; message(LOADINGTABLES,NULL); read_topology_tables();/*module utils.c*/ free_mem(&g_ttnames); /*Create the working table:*/ g_tt_wrk=tt_createNewTable(g_defaultTokenDictSize,g_defaultHashTableSize); /*Check success, if not, halt the system:*/ checkTT(g_tt_wrk,FAILCREATINGWRKTABLE); /*Collect translations from all tables:*/ wrktrans=tt_table[g_tt_wrk-1]->htrans; /*Full toplogies:*/ for(i=0;i<g_tt_top_full;i++){ HASH_TABLE ttrans=tt_table[g_tt_full[i]-1]->htrans; if( ttrans!=NULL ) binary_operations_under_hash_table( ttrans,/*"from"*/ wrktrans,/*"to"*/ -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they are absent in "to", op<0 -> rewrite entries in "to" by the corresponding "from", op==0 -> remove all entries in "to" matching "from"*/ }/*for(i=0;i<g_tt_top_full;i++)*/ /*Internal topologies:*/ for(i=0;i<g_tt_top_int;i++){ HASH_TABLE ttrans=tt_table[g_tt_int[i]-1]->htrans; if( ttrans!=NULL ) binary_operations_under_hash_table( ttrans,/*"from"*/ wrktrans,/*"to"*/ -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they are absent in "to", op<0 -> rewrite entries in "to" by the corresponding "from", op==0 -> remove all entries in "to" matching "from"*/ }/*for(i=0;i<g_tt_top_int;i++)*/ /*Override translations, if present, in wrk table; in loaded tables translations remain to be untranslated!:*/ if( g_ttTokens_table!=NULL ) binary_operations_under_hash_table( g_ttTokens_table,/*"from"*/ wrktrans,/*"to"*/ -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they are absent in "to", op<0 -> rewrite entries in "to" by the corresponding "from", op==0 -> remove all entries in "to" matching "from"*/ /*Now wrk table is ready*/ /*Override translations, if present, in full toplogies:*/ if( g_ttTokens_table!=NULL )for(i=0;i<g_tt_top_full;i++){ HASH_TABLE ttrans=tt_table[g_tt_full[i]-1]->htrans; if( ttrans!=NULL )/*BTW, it CANNOT be a NULL! See, how tt_createNewTableis invoked in the beginning of tt_loadTable, file tt_load.c*/ binary_operations_under_hash_table( g_ttTokens_table,/*"from"*/ ttrans,/*"to"*/ -1);/*see "hash.c"; op>0 -> add enties to "to" from "from", only if they are absent in "to", op<0 -> rewrite entries in "to" by the corresponding "from", op==0 -> remove all entries in "to" matching "from"*/ }/*for(i=0;i<g_tt_top_full;i++)*/ message(DONE,NULL); }/*if (g_ttnames != NULL)*/ /*If only interpret, we need not analyse diagrams:*/ if(is_bit_set(&mode,bitONLYINTERPRET)){ int exitcode; run_init(1);/*module init.c*/ esc_char=mem_esc_char; islast=1; g_nocurrenttopology=1;/*Similar to islast, but specially for topologies.*/ message(CALLTOINTERPRETER,NULL); exitcode=run(number_of_trunslated_lines,array_of_trunslated_lines); message(DONE,NULL); {char endmessage[MAX_STR_LEN]; sprintf(endmessage,EXITCODEFROMINTERPRETER,exitcode); errorlevel=exitcode; halt(endmessage,NULL); } /*Stop running...*/ }/*if(is_bit_set(&mode,bitONLYINTERPRET)*/ /*ok, if we are here then we have to read diagrams...*/ detect_last_diagram_number();/*module last_num.c*/ message(LOOKINGFORFIRRSTDIAGRAM,NULL); scaner_init(input_name,0);/*module init.c*/ skip_until_first_actual_diagram();/*module read_inp.c*/ create_table(&dbuf,&dtable,MAX_VERTEX,MAX_I_LINE,ext_lines);/*module utils.c*/ create_table(&wrkbuf,&wrktable,MAX_VERTEX,MAX_I_LINE,ext_lines); message(DONE,NULL); message(READDIAGRAMS,NULL); for(i=start_diagram;!(i>finish_diagram);i++){/*begin main loop*/ skip_to_new_diagram();/* module read_inp.c Reads until '['*/ if(i % STEP_INDICATOR == 0){ char mes[MAX_STR_LEN]; sprintf(mes,INDICATE_MESSAGE,i,finish_diagram); message(mes,NULL); }/*if(i % STEP_INDICATOR == 0)*/ /* Check should we process this diagram:*/ if (set_in(i % 250,dmask[i / 250])) continue; new_diagram();/*module read_inp.c. Some initializations before each diagram.*/ detect_number_and_coefficient();/*module read_inp.c This function must receive from scaner exactly 'd###'*/ if(i!=diagram_count) halt(CURRUPTEDINPUT,input_name); create_primary_diagram_table();/*module read_inp.c*/ if ( skiptadpoles && thisistadpole ) continue; define_topology();/*module read_inp.c*/ /*compare_topology() returns 1 if topology is not actual. If topology is undefined, this procedure will call 'out_undefined_topology();' (if bitBROWS is not set) and set bitTERROR. */ if(compare_topology())/*module read_inp.c*/ continue; create_diagram_table();/*module read_inp.c*/ define_prototype();/*module read_inp.c*/ if(!is_bit_set(&mode,bitFORCEDTRUNSLATION)) if(skip_prototype())/*module utils.c*/ continue; create_indices_table();/*module read_inp.c*/ if(must_diagram_be_skipped())/*module utils.c*/ continue; if (is_bit_set(&mode,bitBROWS)) fill_up_diagram_array(count);/*module read_inp.c*/ count++; if(is_bit_set(&mode,bitFORCEDTRUNSLATION)){ if(g_tt_try_loaded>0)/*Automatic momenta distribution mechanism*/ callrun=1; else if( ( is_bit_set(&mode,bitTERROR) )&&(!is_bit_set(&mode,bitBROWS))) callrun=0; else callrun=1; }else{ callrun=( (!is_bit_set(&mode,bitTERROR) )&& (!is_bit_set(&mode,bitBROWS) ) ); } /*Run the interpreter:*/ if(callrun){ build_form_input();/*module read_inp.c*/ run_init(0);/*module init.c*/ esc_char=mem_esc_char; if(run(number_of_trunslated_lines,array_of_trunslated_lines)==HALT) set_bit(&mode,bitRUNSIGNAL); run_clear();/*module init.c*/ if(is_bit_set(&mode, bitSKIP)){ unset_bit(&mode,bitSKIP); count--; }else if((is_bit_set(&mode,bitFORCEDTRUNSLATION))&& (skip_prototype()/*module utils.c*/)){ count--; }else{ if(g_topologyLabel!=NULL){/*First occurence, otherwise will be NULL*/ /*Mark topology as occurred*/ set_bit(g_topologyLabel,0); if(g_tt_try_loaded>0){/*Table were loaded*/ if( topologies[cn_topol].orig==NULL )/*Undefined topology*/ process_topol_tables(0);/*try to find momenta, read_inp.c*/ if(topologies[cn_topol].coordinates_ok==0)/*No coords*/ process_topol_tables(1);/*try to find coordinates, read_inp.c*/ /*Now current topology is marked, and wrk toable is built.*/ }else{ if( topologies[cn_topol].orig==NULL ){/*Undefined topology*/ if( automatic_momenta_group(NULL,cn_topol)==1) /*Now momenta are distributed automatically:*/ set_bit(g_topologyLabel,2); /*Bit 0: 0, if topology not occures, or 1; bit 1: 1, if topology was produced form generic, or 0. bit 2: 1, automatic momenta is implemented, or 0 */ }/*if( topologies[cn_topol].orig==NULL )*/ }/*if(g_tt_try_loaded>0)...else...*/ }/*if(g_topologyLabel!=NULL)*/ output_common_protocol(count);/*module read_inp.c*/ }/*if(is_bit_set(&mode, bitSKIP)) ... else ... else*/ if(is_bit_set(&mode,bitRUNSIGNAL)){ sc_done(); errorlevel=0; halt(RUNSIGNAL,NULL); }/*if(is_bit_set(&mode,bitRUNSIGNAL))*/ }/*if(callrun)*/ }/*end main loop*/ sc_done(); message(DONEDIAGRAMS,NULL); /*Check should we run the interpreter once more:*/ if(is_bit_set(&mode,bitEND)){ /*To use some of specmode operators during "extra call":*/ new_diagram(); run_init(1); esc_char=mem_esc_char; islast=1; g_nocurrenttopology=1;/*Similar to islast, but specially for topologies.*/ cn_topol=top_topol;/*Indicate that there is no special topology */ message(EXTRACALL,NULL); if(run(number_of_trunslated_lines,array_of_trunslated_lines)==HALT){ errorlevel=0; halt(RUNSIGNAL,NULL); } message(DONE,NULL); }/*if(is_bit_set(&mode,bitEND))*/ if (is_bit_set(&mode,bitBROWS)){ message(BROWSERMODEDETECT,NULL); out_browse_head(count);/*module browser.c*/ message(SORTINGDIAGRAMS,NULL); sort_diargams(count);/*module browser.c*/ message(DONE,NULL); message(PRINTINGDIAGRAMS,NULL); print_diagrams(count);/*module browser.c*/ message(DONE,NULL); sort_prototypes();/*module browser.c*/ print_prototypes();/*module browser.c*/ print_all_found_topologies();/*module browser.c*/ print_not_found_topologies();/*module browser.c*/ print_undefined_topologies();/*module browser.c*/ }/*if (is_bit_set(&mode,bitBROWS))*/ errorlevel=0; halt(NOERROR,NULL); return(0);/*Actually, the control can't reach this point*/ }/*main*/
// A quadratic sieve implementation for integers up to 100 bits. N must be composite. mpz_class quadratic_sieve(mpz_class &N) { std::vector<uint32_t> factor_base; mpz_class sqrt_N = sqrt(N); //const unsigned long sqrt_N_long = sqrt_N.get_ui(); // Set the smoothness bound. uint32_t B; { // Approximation of the natural logarithm of N. float log_N = mpz_sizeinbase(N.get_mpz_t(), 2) * log(2); // The optimal smoothness bound is exp((0.5 + o(1)) * sqrt(log(n)*log(log(n)))). B = (uint32_t)ceil(exp(0.56 * sqrt(log_N * log(log_N)))) + 300; } // Generate the factor base using a sieve. { char *sieve = new char[B + 1]; memset(sieve, 1, B + 1); for(unsigned long p = 2; p <= B; ++p) { if(!sieve[p]) continue; if(mpz_legendre(N.get_mpz_t(), mpz_class(p).get_mpz_t()) == 1) factor_base.push_back(p); for(unsigned long i = p; i <= B; i += p) sieve[i] = 0; } delete[] sieve; } std::vector<uint32_t> X; float *Y = new float[SIEVE_CHUNK]; std::vector<std::vector<uint32_t> > smooth; int fails = 0; // The sieve boundary. uint32_t min_x = 0; uint32_t max_x = SIEVE_CHUNK; // Calculate sieve index (where to start the sieve) for each factor base number. uint32_t **fb_indexes = new uint32_t*[2]; fb_indexes[0] = new uint32_t[factor_base.size()]; fb_indexes[1] = new uint32_t[factor_base.size()]; for(uint32_t p = 0; p < factor_base.size(); ++p) { // At what indexes do we start this sieve? Solve the congruence x^2 = n (mod p) to find out. // Results in two solutions, so we do two sieve iterations for each prime in the factor base. uint32_t idxs[2]; mpz_class temp = N % mpz_class(factor_base[p]); tonelli_shanks(temp.get_ui(), factor_base[p], idxs); temp = idxs[0] - sqrt_N; temp = ((temp % factor_base[p]) + factor_base[p]) % factor_base[p]; fb_indexes[0][p] = temp.get_ui(); temp = idxs[1] - sqrt_N; temp = ((temp % factor_base[p]) + factor_base[p]) % factor_base[p]; fb_indexes[1][p] = temp.get_ui(); } float last_estimate = 0; uint32_t next_estimate = 1; // Sieve new chunks until we have enough smooth numbers. while(smooth.size() < (factor_base.size() + 20)) { // Generate our Y vector for the sieve, containing log approximations that fit in machine words. for(uint32_t t = 1; t < SIEVE_CHUNK; ++t) { // Calculating a log estimate is expensive, so don't do it for every Y[t]. if(next_estimate <= (t + min_x)) { mpz_class y = (sqrt_N + t + min_x) * (sqrt_N + t + min_x) - N; // To estimate the 2 logarithm, just count the number of bits that v takes up. last_estimate = mpz_sizeinbase(y.get_mpz_t(), 2); // The higher t gets, the less the logarithm of Y[t] changes. next_estimate = next_estimate * 1.8 + 1; } Y[t] = last_estimate; } // Perform the actual sieve. for(uint32_t p = 0; p < factor_base.size(); ++p) { float lg = log(factor_base[p]) / log(2); for(uint32_t t = 0; t < 2; ++t) { while(fb_indexes[t][p] < max_x) { Y[fb_indexes[t][p] - min_x] -= lg; fb_indexes[t][p] += factor_base[p]; } // p = 2 only has one modular root. if(factor_base[p] == 2) break; } } // Factor all values whose logarithms were reduced to approximately zero using trial division. { float threshold = log(factor_base.back()) / log(2); for(uint32_t i = 0; i < SIEVE_CHUNK; ++i) { if(fabs(Y[i]) < threshold) { mpz_class y = (sqrt_N + i + min_x) * (sqrt_N + i + min_x) - N; smooth.push_back(std::vector<uint32_t>()); for(uint32_t p = 0; p < factor_base.size(); ++p) { while(mpz_divisible_ui_p(y.get_mpz_t(), factor_base[p])) { mpz_divexact_ui(y.get_mpz_t(), y.get_mpz_t(), factor_base[p]); smooth.back().push_back(p); } } if(y == 1) { // This V was indeed B-smooth. X.push_back(i + min_x); // Break out of trial division loop if we've found enou gh smooth numbers. if(smooth.size() >= (factor_base.size() + 20)) break; } else { // This V was apparently not B-smooth, remove it. smooth.pop_back(); ++fails; } } } } min_x += SIEVE_CHUNK; max_x += SIEVE_CHUNK; } uint64_t **matrix = new uint64_t*[factor_base.size()]; // The amount of words needed to accomodate a row in the augmented matrix. int row_words = (smooth.size() + sizeof(uint64_t)) / sizeof(uint64_t); for(uint32_t i = 0; i < factor_base.size(); ++i) { matrix[i] = new uint64_t[row_words]; memset(matrix[i], 0, row_words * sizeof(uint64_t)); } for(uint32_t s = 0; s < smooth.size(); ++s) { // For each factor in the smooth number, add the factor to the corresponding element in the matrix. for(uint32_t p = 0; p < smooth[s].size(); ++p) toggle_bit(s, matrix[smooth[s][p]]); } // Gauss elimination. The dimension of the augmented matrix is factor_base.size() x (smooth.size() + 1). { uint32_t i = 0, j = 0; while(i < factor_base.size() && j < (smooth.size() + 1)) { uint32_t maxi = i; // Find pivot element. for(uint32_t k = i + 1; k < factor_base.size(); ++k) { if(get_bit(j, matrix[k]) == 1) { maxi = k; break; } } if(get_bit(j, matrix[maxi]) == 1) { std::swap(matrix[i], matrix[maxi]); for(uint32_t u = i + 1; u < factor_base.size(); ++u) { if(get_bit(j, matrix[u]) == 1) { for(int32_t w = 0; w < row_words; ++w) matrix[u][w] ^= matrix[i][w]; } } ++i; } ++j; } } mpz_class a; mpz_class b; // A copy of matrix that we'll perform back-substitution on. uint64_t **back_matrix = new uint64_t*[factor_base.size()]; for(uint32_t i = 0; i < factor_base.size(); ++i) back_matrix[i] = new uint64_t[row_words]; uint32_t *x = new uint32_t[smooth.size()]; uint32_t *combination = new uint32_t[factor_base.size()]; // Loop until we've found a non-trivial factor. do { // Copy the gauss eliminated matrix. for(uint32_t i = 0; i < factor_base.size(); ++i) memcpy(back_matrix[i], matrix[i], row_words * sizeof(uint64_t)); // Clear the x vector. memset(x, 0, smooth.size() * sizeof(uint32_t)); // Perform back-substitution on our matrix that's now in row echelon form to get x. { int32_t i = factor_base.size() - 1; while(i >= 0) { // Count non-zero elements in current row. int32_t count = 0; int32_t current = -1; for(uint32_t c = 0; c < smooth.size(); ++c) { count += get_bit(c, back_matrix[i]); current = get_bit(c, back_matrix[i]) ? c : current; } // Empty row, advance to next. if(count == 0) { --i; continue; } // The system is underdetermined and we can choose x[current] freely. // To avoid the trivial solution we avoid always setting it to 0. uint32_t val = count > 1 ? rand() % 2 : get_bit(smooth.size(), back_matrix[i]); x[current] = val; for(int32_t u = 0; u <= i; ++u) { if(get_bit(current, back_matrix[u]) == 1) { if(val == 1) toggle_bit(smooth.size(), back_matrix[u]); unset_bit(current, back_matrix[u]); } } if(count == 1) --i; } } a = 1; b = 1; // The way to combine the factor base to get our square. memset(combination, 0, sizeof(uint32_t) * factor_base.size()); for(uint32_t i = 0; i < smooth.size(); ++i) { if(x[i] == 1) { for(uint32_t p = 0; p < smooth[i].size(); ++p) ++combination[smooth[i][p]]; b *= (X[i] + sqrt_N); } } for(uint32_t p = 0; p < factor_base.size(); ++p) { for(uint32_t i = 0; i < (combination[p] / 2); ++i) a *= factor_base[p]; } // If a = +/- b (mod N) we found a trivial factor, run the loop again to find a new a and b. } while(a % N == b % N || a % N == (- b) % N + N); b -= a; mpz_class factor; mpz_gcd(factor.get_mpz_t(), b.get_mpz_t(), N.get_mpz_t()); for(uint32_t i = 0; i < factor_base.size(); ++i) { delete[] matrix[i]; delete[] back_matrix[i]; } delete[] combination; delete[] Y; delete[] fb_indexes[0]; delete[] fb_indexes[1]; delete[] fb_indexes; delete[] matrix; delete[] back_matrix; delete[] x; return factor; }
/* set val (0 or 1) to lsb of var */ uint8_t set_lsb(uint8_t var, uint8_t val) { if(val) return set_bit(0, var); else return unset_bit(0, var); }
/* //move, because it would be boring otherwise void fungus::move(int x_change, int y_change) { a=x; b=y; x += x_change; y += y_change; } */ void fungus::ai() { if(check_bit(attributes, DEAD))// || check_bit(attributes, FRIENDLY)) return; other_count++; if(other_count == 6) { other_count = 0; set_bit(attributes, ASLEEP); return; } if(hp < hp_old) { for(unsigned int i=0; i<curr_level->monsters.size(); i++) if(curr_level->monsters[i]->type == type && curr_level->monsters[i]->x >= x-1 && curr_level->monsters[i]->x <= x+1 && curr_level->monsters[i]->y >= y-1 && curr_level->monsters[i]->y <= y+1) { unset_bit(curr_level->monsters[i]->attributes, ASLEEP); curr_level->monsters[i]->energy = curr_level->guy->speed; curr_level->monsters[i]->other_count = 0; } } hp_old = hp; // int colors[6] = { 46, 82, 118, 154, 190, 226 }; //green/yellow (plant) int colors[6] = { 201, 165, 129, 93, 57, 21 }; //purple/blue // int colors[6] = { 196, 202, 208, 214, 220, 226 }; //red/yellow (fire) // int colors[6] = { 52, 58, 64, 70, 76, 82}; //red/grean (sickly); // int colors[6] = { 196, 160, 124, 88, 52, 52 }; //dark red color = colors[other_count]; int direction = range(1,9); int spawn_x = x, spawn_y = y; switch(direction) { case 1: spawn_y--; spawn_x--; break; case 2: spawn_y--; break; case 3: spawn_y--; spawn_x++; break; case 4: spawn_x--; break; case 5: spawn_x++; break; case 6: spawn_y++; spawn_x--; break; case 7: spawn_y++; break; case 8: spawn_y++; spawn_x++; break; } for(unsigned int i=0; i<curr_level->monsters.size(); i++) if(curr_level->monsters[i]->x == x && curr_level->monsters[i]->y == y && curr_level->monsters[i] != this) attack_something(curr_level->monsters[i]); if(curr_level->data->data[spawn_y][spawn_x] == FLOOR) { // if(range(0,2) != 1) // return; for(unsigned int i=0; i<curr_level->monsters.size(); i++) if(curr_level->monsters[i]->x == spawn_x && curr_level->monsters[i]->y == spawn_y && !check_bit(curr_level->monsters[i]->attributes, DEAD)) { if(curr_level->monsters[i]->type != type) attack_something(curr_level->monsters[i]); return; } if(curr_level->guy->x == spawn_x && curr_level->guy->y == spawn_y) { attack_something(curr_level->guy); return; } curr_level->monsters.push_back(new fungus(type,spawn_x, spawn_y, curr_level)); } }