

InterviewSolution
Saved Bookmarks
1. |
Solve : C++ problem? |
Answer» i made a program to GET the factors for a NUMBER but i get weird answers back such as Quote 20 has these factors 3999008,3999008,0,0,0,0for an input of 20. the code is as followsCode: [Select]#include <cstdlib> #include <iostream> using namespace std; void show( int *arr ,int num ); int main(int ARGC, char *argv[]) { int num=0; int numfactor=0; int numarry=0; char error[20]; cout << "what number do you want to factor: "; while (!(cin >> num)) { cout <<"try again"; cin >> error; } for (int i=1;i<=num;i++) if (!(num % i)) numfactor++; int * factor =new int [numfactor]; for (int i=1;i<=num;i++) if (!(num % i)) { cout <<i<<"\n"; factor[numarry]; numarry++; } cout <<num << " has these factors "; show(factor,numfactor); cout <<"\n"; system("PAUSE"); return EXIT_SUCCESS; } void show (int arr[] ,int x) { cout <<arr[0]; for (int i=1;i < x;i++) cout <<","<<arr[i]; }try using longin what variablemy bad, thought you were doing factorials...(but still better to use long in case you want to find factors of very big numbers) you are using c++ and std namespace, so use endl instead of "\n". also you did not assign values to your factors array Code: [Select]using namespace std; void show( int *arr ,int num ); int main(int argc, char *argv[]) { int num=0; int numfactor=0; int numarry=0; char error[20]; cout << "what number do you want to factor: "; while (!(cin >> num)) { cout <<"try again"; cin >> error; } for (int i=1;i<=num;i++){ if (!(num % i)) numfactor++; } int * factor =new int [numfactor]; for (int i=1;i<=num;i++) if (!(num % i)) { cout <<i<<endl; factor[numarry]=i; numarry++; } cout <<num << " has these factors "; show(factor,numfactor); cout <<endl"; return 0; } void show (int arr[] ,int x) { cout <<arr[0]; for (int i=1;i < x;i++) cout <<","<<arr[i]; } thank you THOUGH i have have two questions 1) why should i use endl instead of /n 2)is this the most efficient method of getting factorsyou can see some discussion here and hereQuote from: mat123 on January 06, 2011, 12:08:30 AM 1) why should i use endl instead of /n"\n" is literal, and while compilers will generally condense all the instances of a single literal into one, you shouldn't assume anything as far as the compiler goes. endl is a constant, already defined specifically for you to use with iostream. Quote 2)is this the most efficient method of getting factors No. your iterating from 1 to the number, by one every time. first- one will be a factor of any whole number, 2, there is no need to go past the original number divided by 2, since no number B that is larger then Number A/2 will be a factor of A. Also, consider the numbers 2,3,5,7 and 9. if 2 is not a factor, then you KNOW that no multiple of 2 (4,6,8, etc) is a factor either. same with 3 and it's multiples. And that is just for starters. OK thank you for your help |
|