C++ condesing this code - c++

Ok so I've already simplified/condense it while keeping the functionality,but im only doing C++ for a month and a half.Was at 100 lines of code.Is it possible to declare the variable in the functions arguement and then call them without passing values into the arguemnets?
#include <iostream>
#include <windows.h>
using namespace std;
int primeCheck10 (int j)
{
int count=0;
cout<<"Enter a number between 1 and 10___";
cin>>j;
if(j<1 ||j>10)
{
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int primeCheck100(int j)
{
int count=0;
cout<<"Enter a number between 1 and 100___";
cin>>j;
if(j<1 || j>100){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int checkPrime1000(int j)
{
int count=0;
cout<<"Enter a number between 1 and 1000___";
cin>>j;
if(j<1 || j>1000){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<j; i++)
{
if(j%i==0)
{
count++;
break;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
}
int main ()
{
system("pause");
return 0;
}

Yes, you can condense all the prime checking into a single function pretty easily. I'd change the structure of the code to just check whether a given number is prime, and return a bool to indicate whether it is or not:'
bool isprime(int n) {
int limit = sqrt(n)+1; // only need to check up to sqrt(n)
if (n == 2)
return true;
if (n == 1 || n % 2 == 0) // check if it's 1 or even
return false;
for (int i = 3; i <= limit; i += 2) // not even -- only check odd numbers
if (n % i == 0)
return false;
return true;
}
Then the code to get input and display results would be separate:
void primecheck(int limit) {
std::cout << "Please enter a number between 1 and " << limit;
int j;
std::cin >> j;
if (j<1 || j > limit)
std::cerr << "Invalid value";
static char const *labels [] = { "Not a prime number\n", "Prime number\n" };
std::cout << labels[isprime(j)];
}
It wouldn't be terribly difficult to make it even shorter than this, but we're reaching the point where it would probably end up less readable if you did so.

If I have unserstood correctly you then you are asking about default arguments. For example
#include <iostream>
void f( int i = 10 )
{
std::cout << "i = " << i << std::endl;
}
int main()
{
f();
}

You could just make one method... and add a bounds
int primecheck(int value, int bounds){
int count=0;
cout <<"Enter a number between 1 and " << bounds << "___";
cin>>value;
if(j<1 || value>bounds){
cout<<"Invalid Value\n";
return 0;
}
for(int i=2; i<value/2; i++)
{
if(value%i==0)
{
count++;
}
}
if(count==0)
cout<<"Prime number\n";
else
cout<<"Not a Prime number\n";
return count;
}
This alg is prob not the best way to check for primes though. for instance for(int i=2; i<j/2; i++) in your loop with optimize it. For example 32, 6x6 = 32, 2x16 = 32, 4x8 = 32. The highest number that can be divisible to j or value is half of it because 1 isn't considered under divisibility so the lowest number would be 2. Which is half.

Related

Write a program that will display all prime numbers from the given range

Write a program that will display all prime numbers from the given range. The program must satisfy the following requirements:
a. ask the user of range to display
b. contains the following function:
i. checkRange() – a functions that checks if the entered range is correct or not. A message will be displayed if the range is invalid.
ii. displayPrime() – a function that displays all prime numbers in the given range
NOTE: you will provide the parameter(s) for each function.
here's the code that i made: there is something wrong in my code. I can't pinpoint what is it
#include <iostream>
using namespace std;
int main()
{
int Prime, strt, end, result;
bool isprime=true;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>strt;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
result = Prime(strt,end);
cout<<"Prime numbers in the given range are: "<<result<<endl;
return 0;
}
int Prime(int strt, int end, int num, isprime)
{
int result;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (num = 2; num <= strt/2; ++num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime)
cout << strt << ", ";
++strt;
}
return result;
}
Here is the answer, there are many issues with the code that I won't go through them, ask if you don't understand something
#include <iostream>
using namespace std;
int prime(int strt, int end)
{
bool isprime;
int count;
while (strt<end)
{
isprime=true;
if (strt == 0 || strt == 1)
{
isprime = false;
}
for (int num = 2; num <= strt/2; ++num)
{
if (strt % num == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout << strt << ", ";
++count;
}
++strt;
}
return 0;
}
int main()
{
int strt, end, result;
Again:
cout<<"Start: ";
cin>>strt;
cout<<"End: ";
cin>>end;
cout<<"\n";
if (strt>end)
{
cout<<"Range is Invalid, Try Again."<<"\n";
goto Again;
}
cout<<"Prime numbers in the given range are: ";
prime(strt,end);
return 0;
}
This is Probably the simplest way I can put it for you.
#include<iostream>
using namespace std;
int check_range(int a,int b)
{
if (a > b)
return 0;
else
return 1;
}
int check_prime(int a,int b)
{
bool isprime;
while (a < b)
{
isprime=true;
if (a == 0 || a == 1)
{
isprime = false;
}
for (int i = 2; i <= a/2; i++)
{
if (a % i == 0)
{
isprime = false;
break;
}
}
if (isprime) {
cout <<a<<" ";
}
a++;
}
}
int main()
{
int strt,end;
Repeat :
cout<<"Enter the lower limit of range :";
cin>>strt;
cout<<"Enter the upper limit of range :";
cin>>end;
int p = check_range(strt,end);
if (p)
{
check_prime(strt,end);
}
else
{
cout<<"The range is inappropriate.\n";
goto Repeat;
}
}
Hope you would understand.

Unable to find the error in the code I wrote for a question on loops in C++. Could anyone point it out?

a beginner at coding here.
I was practising loops(c++) when I stumbled upon this problem:-
Write a program in C++ to find the perfect numbers between 1 and 500. (6,28 and 496)
Perfect number: It is a positive integer that is equal to the sum of its proper divisors. The smallest perfect number is 6, which is the sum of 1, 2, and 3.
I wrote the following code:-
#include <iostream>
using namespace std;
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
}
return 0;
}
The code is supposed to print that 6, 28 and 496 are perfect numbers.
But instead, it's not printing anything. Haven't been able to find the error yet after checking for 30+ minutes.
Could anyone point out the error?
You forget to re-initialize some variables in your loop.
for seems more appropriate than while here.
Create sub function also help to "identify" scope.
#include <iostream>
bool isPerfectNumber(int n)
{
int sum = 0;
for (int div = 1; div != n; ++div) {
if (n % div == 0) {
sum += div;
}
}
return sum == n && n > 0;
}
int main()
{
for (int i = 2; i != 501; ++i) {
if (isPerfectNumber(i)) {
std::cout << n << " is a perfect number." << std::endl;
}
}
return 0;
}
#include<iostream>
using namespace std;
bool perfect_num(int x);
int main() {
int m, n, x;
cout << "input the range m, n: " << "\n";
cin >> m >> n;
for (x = m; x <= n; ++x) {
if (perfect_num(x)) {
cout << x << " ";
}
}
return 0;
}
bool perfect_num(int x) {
bool flag = false;
//initialize
int sum = 0, i;
//loop 1 to x
for (i = 1; i < x; ++i) {
//judge whether is the factor
if (x % i == 0) {
sum += i;
}
}
//update flag
flag = (sum == x);
return flag;
}
#include<iostream>
using namespace std;
//judge function
bool isPerfectNum(int num){
int tmp = 0;
for (int i = 1; i < num; ++i) {
if (num % i == 0) {
tmp += i;
}
}
return tmp == num;
}
int main(){
cout << "Perfect Number contains: ";
for (int i = 1; i <= 500; ++i){
if (isPerfectNum(i)) {
cout << i << " ";
}
}
cout << "\n";
return 0;
}
at the end of your first loop, you should bring back div and sum to their default value.
int main() {
int n=2; //test numbers from 2 to 500.
int div=1; //divisor for n.
int sum=0; //sum of divisors which divide n.
while (n<=500) {
while (div<n){ //if div divides n, then it will added to sum and incremented, else only incremented.
if (n%div==0){
sum=sum+div;
div++;
} else{
div++;
}
}
if (sum==n){
cout<<n<<" is a perfect number."<<endl;
n++;
} else{
n++;
}
div = 1; // you should bring them back here.
sum = 0;
}
return 0;
}

BinarySearch function not working

I've got a menu that I've been working on, and everything now seems to work, except for the binary search function. I am entering the size of the array, filling the array, printing it, then sorting it with my chronological menu, and then when I do sequential search, it seems to work. However, binary search does not even return -1 to indicate that the number was not found, the program just stops. Suggestions? Thanks.
#include<iostream>
#include <cmath>
#include <cstdlib>
using namespace std;
int size=0; //global variable size
int a[100]; //global array
int getSize()
{
cout << "Array Size: ";
cin >> size;
return size;
cout << endl;
}
int sequentialSearch(int n)
{
for(int i=0;i<size;i++)
{
if(n==a[i])
{
return (i+1);
}
}
return -1;
}
int binarySearch(int n)
{
int low=0,high=size,mid;
while(low<=high)
{
mid=(low+high)/2;
if(a[mid]==n)
{
return mid+1;
}
else if(a[mid]>n)
high=mid-1;
else if(a[mid]<n)
low=mid-1;
}
return -1;
}
void sort1()
{
int i, j;
for (i = 0; i < size-1; i++)
{
for (j = 0; j < size-i-1; j++)
if (a[j] > a[j+1])
{
int temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
void sort2()
{
int i, j, m;
for (i = 0; i < size-1; i++)
{
m = i;
for (j = i+1; j < size; j++)
{
if (a[j] > a[m])
m = j;
}
int temp=a[m];
a[m]=a[i];
a[i]=temp;
}
}
void printMenu()
{
cout<<"0. Exit\n";
cout<<"1.Get the size needed for todays use of the array \n";
cout<<"2.Fill an array with random numbers from 1-100 \n";
cout<<"3.Print the array with position numbers \n";
cout<<"4.Sort the array in ascending sequence \n";
cout<<"5.Sort the array in descending sequence \n";
cout<<"6.Sequential search of the array for a target\n";
cout<<"7.Binary search of the array for a target\n";
}
void printTheArray()
{
for(int i=0;i<size;i++)
{
cout<<a[i]<<" is at position :"<<i+1<<endl;
}
}
void fillWithRandom()
{
for(int i=0;i<size;i++)
{
int x=rand()%101;
a[i]=x;
}
}
void dispatch(int ch)
{
switch(ch)
{
case 1:cout<<"Size of array :"<<getSize() << endl;
break;
case 2:fillWithRandom();
break;
case 3: printTheArray();
break;
case 4:sort1();
break;
case 5:sort2();
break;
case 6:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res1=sequentialSearch(t);
if(res1!=-1)
cout<<"Found in position :"<<res1<<endl;
else if(res1==-1)
cout<<"Not Found \n";
break;
}
case 7:
{
cout<<"Enter the number you want to search\n";
int t;
cin>>t;
int res=binarySearch(t);
if(res!=-1)
cout<<"Found in position :"<<res<<endl;
else if(res==-1)
cout<<"Not Found \n";
break;
}
default:cout<<"wrong choice\n";
}
}
int main ()
{
printMenu();
int choice;
cout<<"Type in a choice"<<endl;
cin>>choice;
while(choice!=0)
{
dispatch(choice); // one big switch statement
printMenu();
cout<<"Type in a choice"<<endl;
cin>>choice;
}
cout << endl;
// wrap-up
cout << "This program is coded by Troy Wilms" << endl; // fill in your name
// stops the program to view the output until you type any character
return 0;
}
for example, if you try finding 4 in list {1, 3, 5}, low will be always 0 and high will be always 2. because of the code 'low = mid - 1' I think it should be changed to 'low = mid + 1'

Extracting a subsequence from an array

I'm trying to solve an algorithm for extracting a subsequence from an array. It should display the longest subsequence of prime numbers. I have written the whole algorithm but I still get an infinite cycle and I can't figure out where and why. I'm incrementing both indices and modifying the first index at the end, but it is still not working. Thanks a lot !!!
P.S: citire reads the array, prim detects if a number is prime or composed, afisare displays the subsequence and detSecv determines the longest subsequence.
#include <iostream>
#include <math.h>
using namespace std;
void citireSecv(int &n,int x[50])
{
cout<<"Da n: ";
cin>>n;
for(int i=1;i<=n;i++)
{
cout<<"Da un nr: ";
cin>>x[i];
}
}
int prim(int n)
{
int d=2;
while(d<=sqrt(n) && n%d!=0)
{
if(d==2)
d=3;
else
d=d+2;
}
if(d>sqrt(n)) return 1;
else return 0;
}
void afisare(int n,int x[50],int st,int f)
{
for(int i=st;i<=f;i++)
cout<<x[i]<<" ";
}
void detSecv(int n,int x[100],int &st,int &f)
{
st=1; f=0;
int i=1,j;
while(i<=n-1)
{
while(i<=n-1)
{
if(prim(x[i])==0 && prim(x[i+1])==0) i++;
}
j=i+1;
while(j<=n-1)
if(prim(x[j])==0 && prim(x[j+1])==0) j++;
if((j-i) > (f-st))
{
st=i;
f=j;
}
i=j+1;
}
}
int main()
{
int n,x[100],st,f;
citireSecv(n,x);
detSecv(n,x,st,f);
afisare(n,x,st,f);
return 0;
}
Input data:
n=2
First number is: 5
Second number is: 7
Probably just one of many issues with that code:
while(i<=n-1)
{
if(prim(x[i])==0 && prim(x[i+1])==0) i++;
}
j=i+1;
while(j<=n-1)
if(prim(x[j])==0 && prim(x[j+1])==0) j++;
There are two potential infinite loops here. If the conditions in the while don't return true on the first iteration, i (or j) will never get incremented, and you will have your infinite loop. You should almost always increment such variables outside of any conditions.
With a slight change in your code, you make it work, and one thing, you don't need to start array with index 1. you can always start with index zero.
for(int i=1;i<=n;i++)
{
cout<<"Da un nr: ";
cin>>x[i];
}
try to check for a case when no prime subsequence is found, while printing.
void detSecv(int n, int *x, int &start, int &end)
{
start = -1;
end = -1;
int i=0,j;
while(i < n) {
if(prim(x[i])) {
j = i + 1;
while(j < n)
if(prim(x[j])) j++;
else break;
} else {
i++;
continue;
}
if((j-i) > (end - start)) {
start = i;
end = j-1;
}
i=j+1;
}
}
This is a better way to verify if a number is prime or not
bool IsPrime(int number) {
int primeStep = 2;
double stepLimit = sqrt(number);
while(primeStep <= stepLimit)
{
if(number % primeStep == 0)
return false;
primeStep += 1;
}
return true;
}
And nou you can apply that function for each number in your array, and if it's prime , you add it in a new array like this:
void detSecv(int numberOfItems,int *arrayOfNumbers)
{
int arrayOfPrimeNumbers[50] = {};
int index = 0;
for(int i = 0; i < numberOfItems; i++)
{
if(IsPrime(arrayOfNumbers[i])){
arrayOfPrimeNumbers[index] = arrayOfNumbers[i];
index += 1;
}
}
int secondIndex = 0;
while(arrayOfPrimeNumbers[secondIndex] != 0)
{
cout << arrayOfPrimeNumbers[secondIndex] << " ";
secondIndex += 1;
}
}

deciding if a number is perfect or prime

the problem is :
"Write a function to find out if a number is a prime or perfect number."
so far i have worked on the perfect part first and this is what i have:
#include <iostream>
using namespace std;
bool perfectNumber(int);
int main()
{
int number;
cout<<"Please enter number:\n";
cin>>number;
bool perfectNumber(number);
return 0;
}
bool perfectNumber(int number)
{
int i;
int sum=0;
for(i=1;i<=number/2;i++)
{
if(number%i==0)
{
sum+=i;
}
}
if (sum==number)
return i;
else
return 0;
}
HOWEVER, there seems to be errors on this code.
I have looked over the book but nothing talks about this topic.
i would like to get advice on how to fix this code.
thanks!
bool perfectNumber(number);
This does not call the perfectNumber function; it declares a local variable named perfectNumber of type bool and initializes it with the value of number converted to type bool.
In order to call the perfectNumber function, you need to use something along the lines of:
bool result = perfectNumber(number);
or:
bool result(perfectNumber(number));
On another note: if you are going to read input from a stream (e.g. cin>>number), you must check to be sure that the extraction of the value from the stream succeeded. As it is now, if you typed in asdf, the extraction would fail and number would be left uninitialized. The best way to check whether an extraction succeeds is simply to test the state of the stream:
if (cin >> number) {
bool result = perfectNumber(number);
}
else {
// input operation failed; handle the error as appropriate
}
You can learn more about how the stream error states are set and reset in Semantics of flags on basic_ios. You should also consult a good, introductory-level C++ book for more stream-use best practices.
void primenum(long double x) {
bool prime = true;
int number2;
number2 = (int) floor(sqrt(x));// Calculates the square-root of 'x'
for (int i = 1; i <= x; i++) {
for (int j = 2; j <= number2; j++) {
if (i != j && i % j == 0) {
prime = false;
break;
}
}
if (prime) {
cout << " " << i << " ";
c += 1;
}
prime = true;
}
}
bool isPerfect( int number){
int i;
int sum=0;
for(i=1;i<number ;i++){
if(number %i == 0){
cout<<" " << i ;
sum+=i;
}
}
if (sum == number){
cout<<"\n \t\t THIS NUMBER >>> "<< number <<" IS PERFECT \n\n";
return i;
}else if (sum |= number) {
cout<<"\nThis number >>> " << number <<" IS NOT PERFECT \n\n";
return 0;
}
}
#pragma hdrstop
#include <tchar.h>
#include <stdio.h>
#include <conio.h>
//---------------------------------------------------------------------------
bool is_prim(int nr)
{
for (int i = 2; i < nr-1; i++) {
if (nr%i==0) return false;
}
return true;
}
bool is_ptr(int nr)
{
int sum=0;
for (int i = 1; i < nr; i++) {
if (nr%i==0) {
sum=sum+i;
}
}
if (sum==nr) { return true;
}
else return false;
}
#pragma argsused
int _tmain(int argc, _TCHAR* argv[])
{
int numar;
printf ("Number=");scanf("%d",&numar);
if (is_prim(numar)==true) { printf("The number is prime");
}
else printf("The number is not prime");
if (is_ptr(numar)==true) { printf(" The number is perfect");
}
else printf(" The number is not perfect");
getch();
return 0;
}