Why integer overflow not cycling?

Imagine we have 8-bit integer. So we can store integers from -128 to 127. so if we append 2, it will cause Arithmetic operation ‘127 + 2’ (on type ‘Int8’) results in an overflow. Since the very left bit is sign-bit the result should be changed sign-bit + rest of the value and should be -1 in Int8 (correct me if I’m wrong). But almost every time I try to hack the memory and add sum overflow value to a number, it will become some random number and I don’t know why.

The question is why it is not cycled to the reversed number and what is that random number (where did it came from).

Почему, если мы присваиваем переменной b (типа Integer) переменную a (типа int) программа работает, а если наоборот, выдаёт ошибку?

public class Smm extends Monster {     int a;     Integer b;      public static void main(String[] args) {         Smm smm = new Smm();         smm.eat();     }     public void eat(){         a=b;         System.out.println(a);         System.out.println(b);      }     } 

Java: How do I read integer from the standard input, while handling error cases in a sophisticated way?

I want to read a simple integer from the console. But what if the user enters a string instead of an integer? How should I handle this case in a good manner? This is my code:

public static void main( String[] args )     {         Scanner keyboard = new Scanner(System.in);         System.out.println( "Please, enter the number of orders: " );         int orders = -1;         if (keyboard.hasNextInt()) {             orders = keyboard.nextInt() ;          } else {             System.out.println("Sorry, couldn't understand you!");         }     } 

Obviously it works, bit I am concerned that this solution was posted in 2010… is there a better way to handle such situation?

Convert integer to full text string duration

I have a function I have written in VB for use in SSRS 2012. It takes an integer and converts it to full text duration – for example 900 becomes “15 minutes”, 9000 becomes “2 hours 30 minutes”, and 7201 is “2 hours 1 second”.

The code works, and is:

Public Function SecondsFullText(ByVal TotalSeconds As Integer) As String      Dim hours As Integer = new Integer()     Dim minutes As Integer = new Integer()     Dim seconds As Integer = new Integer()      Dim hourString as String = ""     Dim minuteString as String = ""     Dim secondString as String = ""      hours = floor(TotalSeconds / 3600)     minutes = floor((TotalSeconds mod 3600) / 60)     seconds = (TotalSeconds mod 3600) mod 60      If hours = 1 Then         hourString = Cstr(hours) & " hour"     Else If hours > 1 Then         hourString = Cstr(hours) & " hours"     End If      If minutes = 1 Then         minuteString = Cstr(minutes) & " minute"     Else If minutes > 1 Then         minuteString = Cstr(minutes) & " minutes"     End If      If seconds = 1 Then         secondString = Cstr(seconds) & " second"     Else If seconds > 1 Then         secondString = Cstr(seconds) & " seconds"     End If      If hours > 0 and (minutes > 0 or seconds > 0) Then         hourString = hourString & " "     End If      If minutes > 0 and seconds > 0 Then         minuteString = minuteString & " "     End If      return hourString & minuteString & secondString End Function 

My question is: how do I make this better? It seems very clunky, with too many IFs to handle the different possibilities for single/plural, spaces, etc. I feel that this can be better, but I’m not sure how.

Warning comparison between pointer and integer – o que é?

durante a compilação do código em linguagem C me apareceu este erro:

[Warning] comparison between pointer and integer 

em relação a esta etapa do código:

        if(livro > TAM) {             printf("------- Você já cadastrou o maximo de livros ! -------");         } 

Sendo “livro” um struct:

struct fichaLivro {     int cod;     char obra[50];     char autor[50];     char editora[50]; }livro[TAM]; 

e TAM uma constante:

#define TAM 5 

Alguém poderia me explicar o que esta acontecendo e como posso solucionar o mesmo?

código completo para melhor compreensão:

#include <stdio.h> #include <stdlib.h> #include <string.h>  /*Definindo tamanho*/ #define TAM 5  /*--Definindo a struct--*/ struct fichaLivro {     int cod;     char obra[50];     char autor[50];     char editora[50]; }livro[TAM];   int main(void) {      int opc, i;       /*--Menu--*/     printf("------- menu -------\n\n");     printf("1 - Cadastrar novos livros\n");     printf("2 - Ver livros cadastrados\n");     printf("3 - sair\n");        scanf("%d", &opc);      switch(opc) {          case 1:             /*--Cadastro do Livro--*/         system("cls");          for (i = 0; i < TAM; i++) {          printf("\n---------- Cadastrar Livro -----------\n\n\n");          livro[i].cod = i;         printf("Insira o nome da Obra: ");         fflush(stdin);         fgets(livro[i].obra, 50, stdin);          printf("Insira o nome do autor: ");         fflush(stdin);         fgets(livro[i].autor, 50, stdin);          printf("Insira o nome da Editora: ");         fflush(stdin);         fgets(livro[i].editora, 50, stdin);         }          printf("\n====== Livros cadastrados com sucesso! ======\n\n");          if(livro > TAM) {             printf("------- Você já cadastrou o maximo de livros ! -------");         }          system("pause");         break;          case 2:             /*--Livros Cadastrados--*/          printf("Nome da obra: %d", livro[i].cod);         printf("Nome da obra: %d", livro[i].obra);         printf("Nome da obra: %d", livro[i].autor);         printf("Nome da obra: %d", livro[i].editora);          system("pause");         break;          case 3:             /*-- Sair --*/         printf("\n====== Obrigado por vir! ======\n\n");         break;          default:             printf("------- Opção Invalida ! -------\n");         break;     } } 

No caso como posso informar que o usuário cadastrou o máximo de livros sem comparar array com constante?

output – code of finding a pair of items the list in a given list whose sum is equal a given integer

I have been trying to write a program which checks if there are any two items in some list L whose sum is equal to a given integer S, and prints those two items found. The program provides an error message of “!ok” when there is no solution available.

Input: On the first line there will be an integer T representing the number of test cases, followed by 2 input lines for each test case: On the first line of each test case, there will be 2 integers S and E, where S is the expected sum and E is the number of elements in the list. On the second line, there will be E integers separated by a space. Each integer represents an element of the list L. The elements are not sorted in any way and some could have the same value. In cases where the number E is 0, the second line will be empty.

All values for the elements of list L will be in the same range as the value S.

output: For each test case , the output should one contains ass following: If there is an unique solution, two elements x and y (of the list L) should be printed, separated by a single space. If there are multiple solutions- only the first complete pair that appears on the list and provides the correct sum will be printed. If there is no solution- the error message “!OK” should be printed.

Constraints and notes:

1≤T≤1000

-10^6≤S≤10^6​

0≤E≤2⋅10^4

The sum of values of E is at most 10^7

In order to perform that task, I Have tried to use hash-table , since using arrays might be problematic in this case considering run time complexity.

Here is my code:

#include <iostream> #include <bits/stdc++.h> #include <set>  using namespace std;  int main()   {      long long  int   numberElements=0, number;     long long  int  sum=0, temp;     unordered_set<long long int> s;      bool found=0;     int numberCases;     cin >> numberCases;      for(int c = 1; c<=numberCases; c++)     {         s.clear();          cin >> sum;          found=0;         cin>> numberElements;         if(numberElements==0)             cout << "!OK" <<endl;           else         {          for(long long int  i = 0; i< numberElements && found==0; i++)           {              cin >> number;             if (sum==(number+number))              {              if (s.find(number)!=s.end() )               {                cout<<number<<" "<<number<<endl;                found=1;               }              }             else              {                if(s.find(number)==s.end())                  s.insert(number);                   temp = sum - number;                  if (s.find(temp)!=s.end())                { cout<<temp<<" "<<number<<endl;                  found=1;                 }              }            }            if (found==0)            cout << "!OK" <<endl;        }   }      return 0; } 

For the following input:

6 8 4 1 2 4 4 8 4 1 2 7 9 8 4 1 2 8 9 8 4 4 5 3 4 8 4 4 1 1 8 8 4 -1 1 9 8 

The expected output is:

4 4 1 7 !OK 3 5 !OK -1 9 

whereas the output of my code is actually:

1 7 1 8 4 5 !OK !OK 

I have been trying to detect the source of the problem in my code that causes the unwanted output, but till my efforts have risen no success. Any help would be very appreciated.

Flow Free as an integer programming

Flow Free is a popular mobile phone game where the problem is to connect the pieces . Wikipedia suggests this is equivalent to Number Link puzzles and as such is NP-complete.

Supppse we wanted to write a solver for this kind of puzzle. This could be considered a type of integer programming problem, where each square is indexed by a variable. So if the puzzle is $ N \times N$ there are $ N^2$ variables and a number of restrictions.

Somehow we could encode the restriction there’s a single path connecting the dots on each vertex. And that every vertex must be covered.

Is this equivalent to one of the more standard CS problems such as set-cover or SAT?

enter image description here

Related: Are "Flow Free" puzzles NP-hard?

Is every positive integer the rank of an elliptic curve over some number field?

For every positive integer $ n$ , is there some number field $ K$ and elliptic curve $ E/K$ such that $ E(K)$ has rank $ n$ ?

It’s easy to show that the set of such $ n$ is unbounded. But can one show that every positive integer is the rank of some elliptic curve over a number field?

The analogous question for a fixed number field is expected to have a negative answer (c.f. e.g., this question) but is still conjectural. But I wonder if one might be able to prove a positive answer to the question I asked above.