Negative long is returned? - iteration

In this iterative factorial equation any number that I pass through greater than 39 appears negative. Why is this
public static void main(String[] args)
{
long var = formula(40);
if(var != 0){
System.out.print(var);
}
else{return;}
}
public static long formula(final int n) {
if (n < 0) {
System.err.println("No negative numbers");
return 0;
}
long ans = 1;
for (int i = 1; i <= n; i++) {
ans *= i;
}
return ans;
}
}

It is because of something called overflow. There are limits to the values that certain types can hold. If you go past the limit on an integer type's value, you encounter integer overflow. Here's a link about integer overflow with some more specifics.
The gist is that a factorial is an exponential function that grows rapidly, so it doesn't take long to wind up with a value that will not fit into a long integer. When you see negative numbers it's because you have exceeded this limit. The limit is platform dependent, but is often around 4,294,967,295 for an unsigned long int.
Using the limit above, you would only be able to calculate factorials up to 12!, 13 and above would overflow.

Related

How do I call functions within this code? Im using the visual studio software. keep getting errors that array1 and 2 are undefined

enter image description here
Sorry im new to coding . I have searched up possible solutions for this on here but they didnt work. Im also confused on why some code appears grey compared to the rest.
https://1drv.ms/w/s!Ag8vVFKVPyOg6HeYLehGjQKdvl_3?e=QHY6t9
#include <stdio.h>
// initialised variables
int i = 0;
int count = 0;
void displayfunction(void);
int month = 0;
void highervalues(float array1[12], float array2[12]);
void highervalues(float array1[12], float array2[12]) {
for (i = 12; i > 0; i--) {
if (array2[i] > array1[i]) {
count = count + 1;
}
}
}
//Reading values for array1 and array2
void displayfunction(void) {
highervalues(array1[12] , array2[12]);
for (i = 0; i < 12; i++)
{
month = month + 1; // month increases by 1 after each input
printf_s("enter values for year 1 month %d", month);
scanf_s("%f", &array1[i]);
}
for (month = 12; month > 0; month--) {
}
for (i = 0; i < 12; i++) {
month = month + 1;
printf_s("enter values for year 2 month %d", month);
scanf_s("%f", &array2[i]);
}
}
/*comapring 2 arrays and increasing count value if there are any value in array2
are greater than array1*/
int main() {
displayfunction();
int array1[12];
int array2[12];
}
You have a fundamental misunderstanding of variable scope
int main() {
displayfunction();
int array1[12];
int array2[12];
}
Those arrays are only available in main. If you want other functions to operate on them you have to pass them as paramters to those functions. Plus they dont exist at the point where you try to call displayFunction
So change
void displayfunction(void)
to
void displayfunction(float array1[12], float array2[12])
then in main do
int main() {
int a1[12];
int a2[12];
displayfunction(a1, a2);
}
Note that I have changed the names here just to emphasise that its the not the fact that the names are the same thats important.

How do I create an application that prompts the user for an integer and returns the number of digits it has?

I've started writing this code down, and I want to find the return of the number digits it has after the user prompts for the an integer. Where do I begin with this solution?
I'm still currently new to Dr Java coding. However, I've tried researching these methods, and I cannot find an example for this solution.
public class Recursion {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter an integer.");
int digit = input.nextInt();
input.close();
}
}
I expect it needs a recursion or method for this problem, and I believe it needs to return to the number digit, but I am not sure if it's correct.
you can use this function to count number of digits:
function digits_count(n) {
var count = 0;
if (n >= 1) ++count;
while (n / 10 >= 1) {
n /= 10;
++count;
}
return count;
}

complexity of calling a function with a for loop

Im quite new to computational complexity, but i know that a nested for loop will give O(n^2). in my case i have a for loop that calls a function which has a for loop within it. will the complexity be O(n) or worse?
public static void main(String[] args) {
for(int i = 0; i < 10; i++){
if(i != 0){
System.out.println();
printt(i);
}
}
}
public static void printt(int i){
for(int j = 0; j <= 10; j++ ){
if(j !=0 ){
System.out.print(j*i+" ");
}
}
}
}
Think of the number of print statements(the second one itc) that are executed if you run this snippet of code.
The easiest way to reason about this is to go ahead and run the program, and you will notice that you have 81 values being printed out, which tells you that you have 9 calls to the nested function for each run of the outer loop (9 time again). So it ends up being O(n^2).

How to print out the digits of an integer of any length?

This program is works as long as the divide variable is of the same base 10 power as the variable num, in this case the number is 12345 so divide needs to be 10000. While this works for 5 digit numbers, anything with more or less than 5 digits will not have their individual digits printed out. How do I configure divide to have be of the same base 10 power as num automatically?
public class lab5testing
{
public static void main (String args[])
{
int num = 12345, digit = 0, divide = 10000;
if (num != 0)
{
while(num != 0 )
{
digit = ((num/divide)%10);
System.out.println(digit);
divide /= 10;
if (divide == 0)
{
num = 0;
}
}
}
else
{
System.out.println(num);
}
}
}
Maybe you should try with this :
int length = (int)(Math.log10(num)+1);
and then :
int divide = Math.pow(10,lengh);

How to calculate Big O Execution Growth Rate?

I just want to know the break down for the Big O execution growth rate for this code, I have try to calculate it but it I got the for loops wrong. so I am completely stuck on this now.
void doInter(int setA[], int setB[], int sizeA, int sizeB)
{
const int MAX = 10;
int sizeR;
int results [MAX];
// validate sizeA and sizeB
if ((sizeA == 0) || (sizeB == 0))
{
cout << "one of the sets is empty\n";
}
// save elements common to both sets
for (int i = sizeR = 0; i < sizeA; i++ )
{
if (member(setB, setA[i],sizeB))
{
results[sizeR++] = setA[i];
}
}
{
cout << results[i] << " ";
}
cout << "}" << endl;
}
bool member (int set[], int n, int size)
{
for (; size > 0; --size)
{
if (set[size-1] == n)
{
return true;
}
}
return false;
}
The complexity of this code is O(sizeA * sizeB). It is relatively easy to compute - first compute the complexity of the inner function member - this is a single cycle and in the worst case it will perform sizeB iterations. Now in the outer function you call this function in a cycle of size sizeA. Thus the overall complexity is the two complexities multiplied. The remaining operations are relatively simple with regards to this two cycles.
Also an example where this complexity is achieved is easy to see - use two arrays with no common elements.